Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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__).

Post a Comment for "Why Use Getattr() Instead Of __dict__ When Accessing Python Object Attributes?"