Search code examples
pythonintrospection

Why use getattr() instead of __dict__ when accessing Python object attributes?


In source examples and SO answers that have some degree of Python object introspection, a common pattern is:

getattr(some_object, attribute_name_string)

Is there a reason why this pattern is preferred to:

some_object.__dict__[attribute_name_string]

which seems to be more directly showing what's going on? Is it because the latter is too close to a particular implementation in CPython that may be subject to change?

NB Original question incorrectly identified the popular idiom as:

some_object.__getattr__(attribute_name_string)

Solution

  • some_object.__getattr__ is not a common pattern. getattr(some_object, attribute_name_string) is the proper way of accessing attributes dynamically.

    Not all instances have a __dict__ attribute; a class that uses __slots__ for example won't have that attribute. Next, attributes are not necessarily found on the instance, but are class attributes instead. getattr() will find those, looking at __dict__ will not find them. Attributes on the class may also depend on the descriptor protocol.

    There may be uses for direct access to the __getattr__ hook or the __dict__ attribute, but those are specialised uses only. __getattr__ is only used if the attribute was not first found elsewhere, for example (so for attributes not present on the class or in instance.__dict__).