Managing object attributes in Python is usually simple. You just use the dot notation and call it a day.
But there are times when I don’t know the name of the attribute until the code is actually running. This often happens when I’m dealing with large datasets or building flexible APIs.
In my years of developing Python applications, I’ve found that setattr() and getattr() are lifesavers for these exact scenarios. They allow you to write code that is much more adaptable.
In this tutorial, I’ll show you exactly how to use these functions to handle dynamic data effectively.
Why Use Dynamic Attributes in Python?
Most of the time, we hardcode attributes like user.name or user.email. This works perfectly for static structures.
However, when I’m working with dynamic data, like a CSV file containing US Census data or a JSON response from a financial API, I can’t always predict the keys.
Using dynamic attributes allows me to map data to objects on the fly without writing endless if-else statements.
Understand the getattr() Function
The getattr() function is what I use when I need to access an attribute whose name is stored in a variable.
Instead of object.attribute, I use getattr(object, “attribute_name”). It’s incredibly useful for building generic search or display functions.
Access Basic Attributes
Let’s look at a practical example involving US real estate data. Suppose I have a class representing a property listing.
class PropertyListing:
def __init__(self, address, price, state):
self.address = address
self.price = price
self.state = state
# Creating an instance for a listing in Austin, Texas
listing = PropertyListing("123 Maple Ave", 450000, "Texas")
# Traditional way
print(listing.price)
# Dynamic way using getattr
attribute_to_find = "price"
value = getattr(listing, attribute_to_find)
print(f"The value of {attribute_to_find} is: {value}")You can see the output in the screenshot below.

Handle Missing Attributes with Defaults
One thing I love about getattr() is that it prevents the code from crashing if an attribute doesn’t exist.
I can provide a default value as the third argument. This is much cleaner than using a try-except block every time.
# If "square_footage" isn't defined, I can return a default
sq_ft = getattr(listing, "square_footage", "Not Available")
print(f"Square Footage: {sq_ft}")Master the setattr() Function
While getattr() reads data, setattr() writes it. It allows me to assign a value to an attribute dynamically.
The syntax is setattr(object, “attribute_name”, value). I find this essential when I need to hydrate objects from a dictionary.
Dynamic Assignment for US Business Data
Imagine I am processing a list of Fortune 500 companies. I want to update their profiles based on a dynamic feed.
class Company:
pass
nasdaq_company = Company()
# Data received from an external source
update_data = {
"ticker": "AAPL",
"headquarters": "Cupertino, California",
"industry": "Technology"
}
# Dynamically setting attributes
for key, value in update_data.items():
setattr(nasdaq_company, key, value)
print(f"Ticker: {nasdaq_company.ticker}")
print(f"Location: {nasdaq_company.headquarters}")You can see the output in the screenshot below.

Practical Method: Bulk Data Mapping
In my experience, the most common use case for these functions is converting a dictionary (like a JSON response) into an object.
This keeps my code organized and allows me to use dot notation elsewhere in my application.
The Dictionary-to-Object Loop
Here is how I typically handle a batch of employee records for a US-based firm.
class Employee:
def __init__(self, name):
self.name = name
employee_info = {
"department": "Engineering",
"base_office": "New York City",
"is_remote": True,
"salary_grade": "E5"
}
emp = Employee("Sarah Jenkins")
# Mapping the dictionary to the object
for attr_name, attr_value in employee_info.items():
setattr(emp, attr_name, attr_value)
# Now I can access these as regular attributes
print(f"{emp.name} works in {emp.department} located in {emp.base_office}")Advanced Method: Dynamic Function Dispatching
Sometimes, I don’t just want to access data; I want to call methods dynamically.
Since methods in Python are also attributes, getattr() can retrieve a function which I can then execute.
Execute Commands Based on State
Suppose I have a system that processes different US tax forms.
class TaxProcessor:
def process_w2(self):
return "Processing W-2 Wage and Tax Statement."
def process_1099(self):
return "Processing 1099 Misc Income Form."
processor = TaxProcessor()
form_type = "w2" # This could come from user input
# Dynamically get the method
method_name = f"process_{form_type}"
func = getattr(processor, method_name, None)
if func:
print(func())
else:
print("Invalid Form Type")You can see the output in the screenshot below.

Use hasattr() for Safety Checks
Before I try to get or set something, I often use hasattr(). This returns a simple True or False.
It’s a great way to validate if an object supports a specific feature before you try to interact with it.
if hasattr(listing, "price"):
print("This listing has a price defined.")When to Avoid Dynamic Attributes
Even though I use these functions often, they aren’t always the right choice. Overusing them can make your code harder to read.
If your colleagues have to hunt through the code to find where an attribute was created, it can slow down debugging.
I suggest using them only when the attribute names are truly unknown until runtime.
Performance Considerations
I’ve noticed that getattr() is slightly slower than direct dot notation. In most web or data processing apps, you won’t notice the difference.
However, if you are running this inside a loop with millions of iterations, you might want to cache the result or use a different structure.
Build a Dynamic Configuration Class
One of my favorite patterns is creating a configuration class that loads settings from a file or environment variables.
Here is a robust example for a US-based cloud service configuration.
class AppConfig:
def __init__(self, env_vars):
for key, value in env_vars.items():
# I use upper case for config attributes
setattr(self, key.upper(), value)
# Simulating environment variables for a US West server
env_settings = {
"region": "us-west-2",
"db_host": "production-db.example.com",
"timeout": 30
}
config = AppConfig(env_settings)
print(f"Deploying to Region: {config.REGION}")
print(f"Connection Timeout: {config.TIMEOUT} seconds")Combine getattr and setattr for Data Transformation
Sometimes I need to move data from one object to another while transforming it.
In this example, I’ll take a “Raw” data object and move it to a “Cleaned” object if the attribute exists in both.
class RawData:
def __init__(self):
self.raw_zip = "90210"
self.raw_city = "beverly hills"
class CleanData:
def __init__(self):
self.zip_code = None
self.city = None
raw = RawData()
clean = CleanData()
# Mapping with logic
mapping = {
"raw_zip": "zip_code",
"raw_city": "city"
}
for source, target in mapping.items():
val = getattr(raw, source)
if source == "raw_city":
val = val.title() # Capitalize US city names
setattr(clean, target, val)
print(f"Cleaned Record: {clean.city}, {clean.zip_code}")Common Errors and How to Fix Them
I often see beginners forget to provide a default value to getattr(), which leads to an AttributeError.
Always remember that if you don’t provide a default and the attribute is missing, Python will stop your script.
Another mistake is passing the attribute name as a variable without quotes when you actually meant a string literal.
I hope this tutorial helped you understand how to use setattr() and getattr() in your Python projects.
These tools have definitely made my life easier when dealing with unpredictable data structures and complex integrations.
You may also read:
- Default Values and Type Hints in Python Dataclasses
- How to Use Metaclasses in Python
- How type() Works as a Metaclass in Python
- How to Use Class Decorators in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.