Python access class property from string
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
If you have the name of an attribute as a string in Python, the normal way to read it is getattr. This shows up in serializers, command dispatchers, templating helpers, and configuration-driven code. The important part is understanding when dynamic attribute access is appropriate and when it becomes too implicit or unsafe.
The Straightforward Tool: getattr
getattr(obj, name) returns the attribute named by the string name.
This prints 42.
You can also provide a default value so missing attributes do not raise AttributeError:
That is often better than writing a manual if ladder when the attribute name is truly dynamic.
Properties Work Too
In Python, a property is still accessed like an attribute from the outside, so getattr works with @property the same way it works with plain instance attributes.
That matters because the string-driven code does not need to care whether the attribute is stored directly or computed through a property.
When __dict__ Is Not the Right Answer
Developers sometimes try to use obj.__dict__[name]. That works only for attributes stored directly on the instance dictionary. It does not handle:
- properties
- descriptors
- inherited attributes
- methods
- objects using
__slots__
For example:
getattr returns the property value, while __dict__ does not contain it. That is why getattr is usually the correct general-purpose tool.
Accessing Methods by Name
Dynamic lookup also works for methods. The retrieved method is a bound method when accessed through an instance, which means you can call it directly.
This is useful for command dispatch patterns:
The pattern is compact, but it should be constrained carefully if the input comes from outside the program.
Safer Dynamic Access
If attribute names come from users, APIs, or configuration files, avoid exposing the entire object surface. Whitelist the names you support.
This keeps the dynamic behavior but avoids accidental access to internal attributes such as dunder names or helper methods.
Reading Versus Writing
If you need to change an attribute by string name, use setattr:
hasattr is also available when you only need an existence check:
These three functions form the core toolkit for dynamic attribute access in Python.
When Not to Use Dynamic Attribute Access
Do not use string-based lookup just because it feels clever. It is the right tool only when the attribute name is naturally data-driven. If the set of fields is fixed and small, explicit code is usually easier to read and easier to refactor.
Dynamic lookup is powerful, but it reduces static discoverability. That tradeoff is worth making only when the input is genuinely dynamic.
Common Pitfalls
- Using
obj.__dict__[name]as a general replacement forgetattr. It misses properties, methods, and inherited attributes. - Calling
getattron untrusted names without validation. That can expose more of the object than intended. - Forgetting the default argument. If missing attributes are acceptable, pass a fallback instead of catching
AttributeErroreverywhere. - Overusing dynamic lookup when a simple explicit branch would be clearer.
- Confusing reading with writing. Use
getattrfor reads andsetattrfor updates.
Summary
- Use
getattr(obj, name)to access an attribute whose name is stored in a string. - '
getattrworks for regular attributes, properties, and bound methods.' - Prefer it over direct
__dict__access for general attribute lookup. - Whitelist allowed names when the string comes from external input.
- Use
setattrandhasattrfor the matching write and existence-check operations.
Related reading
- Python add item to the tuple
- Python alternative for calculating pairwise distance between two sets of 2d points
- Python Anaconda - How to Safely Uninstall
- Python anaconda access denied
- Python and OpenCV - Improving my lane detection algorithm
- Python and RabbitMQ - Best way to listen to consume events from multiple channels?
- Python argparse command line flags without arguments
- Python argparse default value or specified value
.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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.