Dynamic field access
A program receives a field name from configuration or another runtime source and must inspect that field without hard-coding dot notation.
Python · Function
getattr() retrieves an attribute using a string name. It can return a fallback for missing attributes or raise AttributeError when no fallback is supplied.
getattr() receives an object and a string naming an attribute, then returns that attribute's value. An optional default is returned when the attribute is missing; without one, the lookup raises AttributeError. Attribute names do not have to be valid Python identifiers.
getattr(object, name[, default])| Name | Type | Description |
|---|---|---|
object | object | The object whose attribute is inspected. |
name | str | A string containing the attribute name to retrieve. |
default | object, optional | Fallback returned if the named attribute does not exist. |
The value of the named attribute, or default when supplied and the attribute is absent; otherwise it raises AttributeError.
class Config:
timeout = 30
config = Config()
name = "timeout"
print(getattr(config, name, 10))
print(getattr(config, "missing", 10))Looks up an attribute whose name is stored in a string and supplies 10 when that attribute is absent.
A program receives a field name from configuration or another runtime source and must inspect that field without hard-coding dot notation.
Code supports optional attributes across objects with different interfaces and needs a value when a field is unavailable.
A framework or utility needs to pair runtime attribute reads with the documented attribute-writing counterpart, setattr().
getattr() takes an object and a string attribute name, returning the named attribute's value. Its optional third argument is returned if the attribute is absent; otherwise the function raises AttributeError.
Follow-up: Can the name contain characters that are not valid in an identifier? Yes: the documentation says the name need not be a Python identifier.
The attribute name must be a string, and the function performs a dynamic lookup equivalent to accessing that attribute directly when it exists. The optional default distinguishes a fallback lookup from an exception-producing lookup.
Follow-up: What happens with a double-underscore attribute? The caller must manually apply the name-mangling form because mangling occurs during compilation.
setattr() is described as getattr()'s counterpart. getattr() reads a named attribute, whereas setattr() assigns an arbitrary value to an existing or new attribute when the object permits it.
Follow-up: When might getattr() be preferable to direct access? When the attribute name is computed or when a documented fallback is needed for absent attributes.
setattr()