CKTIS / Python
getattr()
Reads an attribute whose name is supplied as a string.
Version: Python 3.14; repository image, production runtime not attested
Syntax
getattr(object, name[, default])Reads an attribute whose name is supplied as a string.
An optional default is returned when the complete lookup ends with AttributeError. An existing value of None remains a genuine result.
The string name goes through normal attribute lookup, including descriptors. Box.value is present with value None and wins over the default 7. Only a final AttributeError triggers the default. When a property raises AttributeError, a class fallback __getattr__ may still supply the result. An exception such as ValueError from a property getter still propagates.
class Box:
value = None
@property
def broken(self): raise ValueError("bad")
class Recovered(Box):
@property
def missing(self): raise AttributeError
def __getattr__(self, name): return 11
assert getattr(Recovered(), "missing", 7) == 11
b = Box()
assert getattr(b, "value", 7) is None and getattr(b, "absent", 7) == 7
try:
getattr(b, "broken", 7)
except ValueError:
pass
else:
raise AssertionError
Examples
class Box:
value = None
print(getattr(Box, "value", 7))
print(getattr(Box, "missing", 7))
Result
None 7
The string name goes through normal attribute lookup, including descriptors. Box.value is present with value None and wins over the default 7. Only a final AttributeError triggers the default. When a property raises AttributeError, a class fallback `__getattr__` may still supply the result. An exception such as ValueError from a property getter still propagates.