When to use getattr in Python
Source: Dev.to
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")
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)
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
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 be better off using 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 hard‑coded assumptions. Once you see that, it becomes a very precise tool.