How to access get or set object attribute given string corresponding to name of that attribute
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
In Python, accessing an object attribute from a string is a normal part of dynamic code. The built-in tools for it are getattr, setattr, and hasattr, and they are usually preferable to manually manipulating an object's internal dictionary.
Reading an Attribute with getattr
Use getattr when you have the attribute name as a string and want its value.
This prints Ada. The first argument is the object, the second is the attribute name.
You can also provide a default value if the attribute may not exist:
That avoids raising AttributeError.
Writing an Attribute with setattr
Use setattr to update or create an attribute dynamically.
This updates name and creates role. Python objects are flexible enough that many classes allow new attributes to be attached at runtime, although some classes restrict that behavior with __slots__ or custom attribute logic.
Checking Before Accessing
If missing attributes are possible and you want an explicit presence check, use hasattr.
In many code paths, getattr(obj, name, default) is simpler than a separate hasattr check, but both are valid.
Methods Are Attributes Too
In Python, methods are attributes that happen to be callable. That means getattr works for them as well.
This is useful in plugin systems, command dispatchers, or small frameworks that map names to behavior.
When Dynamic Attribute Access Is Appropriate
Dynamic access is most useful when the attribute name truly comes from data:
- reading fields configured at runtime
- applying updates from a form or mapping
- invoking named handlers
- writing serialization or admin tooling
Example of applying validated updates:
This is concise, but it becomes dangerous if the keys are not validated.
Validate Names Before Setting Them
The main risk is setting arbitrary attributes from untrusted input. If keys come from a request body or external file, restrict them to an allowlist.
Without validation, you can accidentally mutate the wrong object state or create attributes the rest of the code never expects.
Attribute Access Versus Dictionaries
Sometimes the right answer is not dynamic attributes at all. If the data is open-ended and key-based, a dictionary is often a better fit than object attributes.
Use attributes when:
- the object has a defined shape
- the fields represent domain state
- properties or methods may enforce behavior
Use a dictionary when:
- keys are arbitrary
- fields vary widely between instances
- the structure is mainly data, not behavior
If you are frequently doing setattr(obj, some_user_string, value) on many unknown names, that is usually a signal that a dictionary or dataclass plus explicit mapping would be cleaner.
Common Pitfalls
The most common mistake is forgetting the default argument to getattr and then being surprised by AttributeError.
Another mistake is setting attributes from untrusted input without validation. Dynamic attribute access is powerful, which means it can also mutate state you never intended to expose.
Developers also confuse instance attributes with dictionary keys. obj["name"] and obj.name are different mechanisms unless the class explicitly implements item access.
Finally, remember that properties, descriptors, and custom __setattr__ methods can add side effects. setattr is not always a plain field assignment.
Summary
- Use
getattr,setattr, andhasattrfor dynamic attribute access in Python. - '
getattr(obj, name, default)is the safest default for optional attributes.' - Methods can also be retrieved dynamically because they are attributes too.
- Validate attribute names before calling
setattrwith external input. - If the data is truly open-ended, a dictionary may be a better model than object attributes.
Related reading
- How to access subdataframes of pandas groupby by key
- How to access the local Django webserver from outside world
- How to activate an Anaconda environment
- How to actually read CSV data in TensorFlow?
- How to add a header keyvalue pair when publishing a message with pika
- How to add a new column to an existing DataFrame
- How to add a new column to an existing DataFrame
- How to add a new row to an empty numpy array
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.