At some point in Python, you realize that writing object.attribute isn’t always enough.
Sometimes:
- The attribute name comes from user input
- Sometimes it comes from configuration
- Sometimes it comes from a loop
- Sometimes you don’t even know which attribute you need until runtime
That’s where getattr comes in.
This post explains what getattr really does, what it doesn’t do, and when it actually makes sense to use it.
The basic idea
Normally, you access attributes like this:
p.name
That works only if you know the attribute name at coding time.
getattr lets you do the same thing, but dynamically:
getattr(p, "name")
If the string "name" matches an attribute on p, Python returns its value.
Are these the same?
Yes, but only in this specific case:
p.name
getattr(p, "name")
They both return the same value.
So why does getattr exist?
Because this is not possible with dot notation:
attr = "nombre"
p.attr # looks for an attribute literally called "attr"
But this works:
attr = "name"
getattr(p, attr)
That’s the key difference.
Why “dynamic” matters
Let’s say you have a simple class:
class Person:
def __init__(self):
self.name = "Alice"
self.age = 30
person = Person()
Now imagine the attribute you want depends on runtime logic:
fields = ["name", "age"]
for field in fields:
print(getattr(person, field))
Without getattr, you’d be forced into using conditionals:
if field == "name":
print(person.name)
elif field == "age":
print(person.age)
Kind of ugly, isn't it?
Default values (avoiding crashes)
Another important feature: safe access.
If the attribute doesn’t exist, you get an AttributeError:
getattr(person, "height")
> AttributeError: 'Person' object has no attribute 'height'
But you can provide a fallback:
getattr(person, "height", 170)
Now your program continues safely.
Accessing methods dynamically
Attributes aren’t just data, methods are attributes too.
class Calculator:
def add(self, x, y):
return x + y
calc = Calculator()
method = getattr(calc, "add")
print(method(2, 3)) # 5
Isn't this cool?
What getattr does not do
getattr is not:
- Faster than dot access
- A replacement for normal attribute access
- Something you should use everywhere
If you know the attribute name in advance, you may better chose the dot notation:
p.name
getattr is for flexibility, not style points.
Final thought
getattr isn’t about being clever.
It’s about writing code that adapts at runtime instead of being locked into hardcoded assumptions.
Once you see that, it becomes a very precise tool.
Top comments (0)