getattr()
getattr(object, name[, default]) Returns:
object · Updated March 13, 2026 · Built-in Functions built-in attributes reflection
The getattr() function returns the value of a named attribute from an object. If the attribute does not exist and a default value is provided, it returns that default instead. If no default is given and the attribute is missing, AttributeError is raised. This function is essential for dynamic attribute access, allowing you to work with attribute names as strings at runtime.
Syntax
getattr(object, name[, default])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
object | object | — | Any Python object from which to retrieve the attribute |
name | str | — | A string containing the attribute name to look up |
default | object | (none) | Value to return if the attribute does not exist |
Examples
Basic attribute access
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(getattr(person, "name"))
# Alice
print(getattr(person, "age"))
# 30
Accessing a non-existent attribute
person = Person("Bob", 25)
# Without default - raises AttributeError
try:
getattr(person, "email")
except AttributeError as e:
print(e)
# 'Person' object has no attribute 'email'
# With default - returns the default value
print(getattr(person, "email", "not provided"))
# not provided
Using getattr with modules
import math
print(getattr(math, "pi"))
# 3.141592653589793
print(getattr(math, "UNKNOWN_CONSTANT", 0))
# 0
Common Patterns
Dynamic attribute access from user input
class Config:
debug = True
max_connections = 100
timeout = 30
def get_config(key):
return getattr(Config, key, None)
print(get_config("debug"))
# True
print(get_config("missing_key"))
# None
Working with dictionaries as objects
class DotDict(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(f"'{type(self).__name__}' has no attribute '{key}'")
data = DotDict({"name": "test", "value": 42})
print(getattr(data, "name"))
# test
Factory pattern with attribute-based instantiation
class Shape:
def draw(self):
return "Drawing shape"
class Circle(Shape):
def draw(self):
return "Drawing circle"
class Square(Shape):
def draw(self):
return "Drawing square"
shapes = {"circle": Circle, "square": Square}
def create_shape(shape_type):
shape_class = getattr(shapes, shape_type.capitalize(), Shape)
return shape_class()
print(create_shape("circle").draw())
# Drawing circle
print(create_shape("triangle").draw())
# Drawing shape
Errors
AttributeError when attribute is missing
If the specified attribute does not exist on the object and no default is provided, getattr() raises an AttributeError. Always provide a default value when the attribute may not exist:
obj = object()
# This raises AttributeError
getattr(obj, "nonexistent")
# This returns None safely
getattr(obj, "nonexistent", None)
TypeError for invalid name type
The name parameter must be a string. Passing a non-string raises TypeError:
getattr(person, 123) # TypeError: attribute name must be string
See Also
- built-in::setattr — set an attribute on an object
- built-in::hasattr — check if an object has an attribute
- built-in::delattr — delete an attribute from an object
- built-in::vars — return the
__dict__of an object