getattr() Get attribute
Last updated: 2026-09-22
getattr() Get attribute
getattr(obj, name[, default]) returns obj.name; returns default if missing (else raises AttributeError).
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
getattr(object, name[, default])
⚙️ Parameters
| object Required | The object to read the attribute from. |
|---|---|
| name Required | The attribute name as a string. |
| default Optional | Value returned if the attribute is missing.(Default:None) |
Returns:The attribute value, or default if the attribute is missing.
💥 Raises
AttributeError— Raised when the attribute is missing and no default is given.TypeError— Raised when name is not a string.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
10
default
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between getattr(obj, 'x', 'default') and obj.x?
AWhen the attribute exists, the results are the same; when it does not, getattr returns 'default' while obj.x raises an AttributeError directly.
QIn what scenarios must I use getattr?
AWhen the attribute name is computed dynamically (from a variable, config, or string concatenation), getattr(obj, attr_name) cannot be replaced by dot syntax.
QHow do getattr and hasattr work together?
AYou can check with hasattr(obj, 'x') and then get with getattr(obj, 'x'); more concisely, getattr(obj, 'x', None) does it in one step.
QWhat happens if I omit default and the attribute does not exist?
AIt raises an AttributeError; if name is not a string it raises a TypeError.