How to Use getattr Function in Python: Syntax and Examples
The
getattr function in Python retrieves the value of an attribute from an object by name as a string. It takes the object, the attribute name, and an optional default value to return if the attribute does not exist.Syntax
The getattr function has this syntax:
getattr(object, name[, default])
object: The object you want to get an attribute from.
name: A string with the attribute's name.
default (optional): A value to return if the attribute is missing, instead of raising an error.
python
value = getattr(object, 'attribute_name', default_value)
Example
This example shows how to use getattr to get an attribute from a simple object and provide a default if it does not exist.
python
class Car: def __init__(self, brand, year): self.brand = brand self.year = year my_car = Car('Toyota', 2020) # Get existing attribute brand = getattr(my_car, 'brand') print('Brand:', brand) # Get missing attribute with default color = getattr(my_car, 'color', 'Unknown') print('Color:', color)
Output
Brand: Toyota
Color: Unknown
Common Pitfalls
Common mistakes when using getattr include:
- Not providing a default value and causing an
AttributeErrorif the attribute is missing. - Passing a non-string as the attribute name, which raises a
TypeError. - Confusing
getattrwith direct attribute access, which does not allow dynamic attribute names.
Always use a string for the attribute name and consider a default value to avoid errors.
python
class Person: def __init__(self): self.name = 'Alice' p = Person() # Wrong: attribute name is not a string # age = getattr(p, 123) # Raises TypeError # Right: attribute name as string age = getattr(p, 'age', 30) # Returns 30 as default print(age)
Output
30
Quick Reference
| Parameter | Description |
|---|---|
| object | The object to get the attribute from |
| name | The attribute name as a string |
| default (optional) | Value returned if attribute is missing |
Key Takeaways
Use getattr(object, 'attribute_name', default) to access attributes dynamically by name.
Always pass the attribute name as a string to getattr.
Provide a default value to avoid AttributeError if the attribute does not exist.
getattr allows safe access to attributes when you don't know the attribute name in advance.
Without a default, getattr raises AttributeError if the attribute is missing.