getattr()

Reads an object’s attribute by a name given as a string, optionally with a default value.

Returns
The attribute’s value, or default.
On this page

Example

#
Python
class Student:
    def __init__(self, name, points):
        self.name = name
        self.points = points

emma = Student("Emma", 250)

print(getattr(emma, "points"))
print(getattr(emma, "level", 1))

for field in ["name", "points"]:
    print(field, "=", getattr(emma, field))
Resultsaved result, you can check it
250
1
name = Emma
points = 250

Definition and usage

#

The getattr(object, "name") function works like object.name, but you give the attribute name as a string. That lets you pick the attribute only while the program is running, for example based on data from a file, settings, or a command typed by the user.

When the attribute does not exist, getattr() raises AttributeError. With a third argument, it returns a default value instead, which is handy for optional fields. You can read a method the same way: getattr(object, "save") returns the method, which you then call with parentheses.

Related functions are hasattr() (whether the attribute exists), setattr() (setting an attribute by name), and delattr() (removing an attribute). Don't use them where a plain dot or a dictionary is enough: code built on names stored in strings is harder to read, and the editor won't catch typos in it.

Syntax

#
Syntax
getattr(object, name)
getattr(object, name, default)

Parameters

#
  • object

    any object

    The object you read the attribute from. It can also be a class or a module.
  • name

    str

    The name of the attribute or method.
  • default

    optional

    The value returned when the attribute does not exist. Without it, AttributeError is raised.

More examples

#
Choosing a method by name
Python
class Robot:
    def forward(self):
        return "Moving forward"

    def left(self):
        return "Turning left"

robot = Robot()
for command in ["forward", "left", "jump"]:
    action = getattr(robot, command, None)
    print(action() if action else f"Unknown command: {command}")
Resultsaved result, you can check it
Moving forward
Turning left
Unknown command: jump
setattr() and a missing attribute
Python
class Settings:
    pass

settings = Settings()
for key, value in {"theme": "dark", "lang": "en"}.items():
    setattr(settings, key, value)

print(settings.theme, settings.lang)

try:
    getattr(settings, "font")
except AttributeError as error:
    print(error)
Resultsaved result, you can check it
dark en
'Settings' object has no attribute 'font'

Good practices

#
  • Reach for getattr() only when the attribute name is really known only while the program runs. Otherwise write object.attribute.
  • When a method name comes from the user, check it against a list of allowed commands, so a method you didn't anticipate can't be called.
  • The function also works with modules: getattr(math, "sqrt")(16) returns 4.0.

Related entries

#

Spotted a mistake or missing an example? Write to us.