The standard
getattr() function doesn't always simply read an attribute. It can invoke a @property, a descriptor, or a custom __getattr__, potentially triggering arbitrary object logic.class User: @property def token(self): print("Loading token...") return "secret"user = User()print(getattr(user, "token"))# Loading token...# secretThis behavior can be undesirable for object analysis tools.
The standard library provides
inspect.getattr_static(), which retrieves an attribute without the usual dynamic access mechanism.from inspect import getattr_staticattr = getattr_static(user, "token")print(type(attr))# <class 'property'>
Instead of executing the property, the function returns the
property object itself. This allows you to inspect the class structure without executing the code associated with reading the attribute.This is useful when working with objects that dynamically create attributes using
getattr.class Config: def __getattr__(self, name): print(f"Loading {name}") return 42config = Config()print(getattr(config, "timeout"))# Loading timeout# 42getattr_static() does not call __getattr__. Therefore, you can check for a missing attribute without any side effects.print(getattr_static(config, "timeout", None))# None
Static retrieval does not guarantee the same value as the standard
getattr(). It may return a descriptor instead of the computed value, and it may not discover some dynamically accessible attributes at all.inspect.getattr_static() allows you to inspect object attributes without executing properties or custom access methods, which is useful when developing debuggers, serializers, and code analysis tools.https://t.me/pythonRe

