Python
programming
object attributes
dynamic attribute access
coding tutorial

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.

Practice algorithms

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.

python
1class User:
2    def __init__(self):
3        self.name = "Ada"
4        self.active = True
5
6
7user = User()
8field_name = "name"
9
10print(getattr(user, field_name))

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:

python
print(getattr(user, "email", "not set"))

That avoids raising AttributeError.

Writing an Attribute with setattr

Use setattr to update or create an attribute dynamically.

python
1class User:
2    def __init__(self):
3        self.name = "Ada"
4
5
6user = User()
7setattr(user, "name", "Grace")
8setattr(user, "role", "admin")
9
10print(user.name)
11print(user.role)

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.

python
1class User:
2    def __init__(self):
3        self.name = "Ada"
4
5
6user = User()
7
8if hasattr(user, "name"):
9    print("name exists")
10
11if not hasattr(user, "email"):
12    print("email is missing")

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.

python
1class Greeter:
2    def hello(self, name):
3        return f"Hello, {name}"
4
5
6greeter = Greeter()
7method_name = "hello"
8method = getattr(greeter, method_name)
9
10print(method("world"))

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:

python
1class Settings:
2    def __init__(self):
3        self.timeout = 30
4        self.debug = False
5
6
7settings = Settings()
8updates = {"timeout": 60, "debug": True}
9
10for key, value in updates.items():
11    setattr(settings, key, value)
12
13print(settings.timeout, settings.debug)

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.

python
1class Settings:
2    def __init__(self):
3        self.timeout = 30
4        self.debug = False
5
6
7allowed = {"timeout", "debug"}
8incoming = {"timeout": 60, "debug": True, "admin": True}
9settings = Settings()
10
11for key, value in incoming.items():
12    if key in allowed:
13        setattr(settings, key, value)
14
15print(settings.__dict__)

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, and hasattr for 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 setattr with external input.
  • If the data is truly open-ended, a dictionary may be a better model than object attributes.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Track 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.

Practice algorithms