DEV Community

guzmanojero
guzmanojero

Posted on

When to use getattr in Python

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
Enter fullscreen mode Exit fullscreen mode

That works only if you know the attribute name at coding time.

getattr lets you do the same thing, but dynamically:

getattr(p, "name")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

But this works:

attr = "name"
getattr(p, attr)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Now imagine the attribute you want depends on runtime logic:

fields = ["name", "age"]


for field in fields:
    print(getattr(person, field))
Enter fullscreen mode Exit fullscreen mode

Without getattr, you’d be forced into using conditionals:

if field == "name":
    print(person.name)
elif field == "age":
    print(person.age)
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

But you can provide a fallback:

getattr(person, "height", 170)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)