Skip to content Skip to sidebar Skip to footer

What Is The Lookup Procedure When Setting An Attribute From A Class Or From An Instance?

Python in a Nutshell describes the lookup procedure when getting an attribute from a class, e.g. cls.name and the lookup procedure when getting an attribute from an instance, e.g.

Solution 1:

For x.y = z, Python looks up x.__setattr__ in a way that bypasses __getattribute__, __getattr__, and x's own __dict__, then calls x.__setattr__('y', z).

A custom __setattr__ can do whatever the heck it wants, but here's the default:

  1. Search type(x).__mro__ for a __dict__ entry matching the attribute name.

  2. If this search finds a descriptor descr with a __set__ method (looking up __set__ the same way we looked up __setattr__), call descr.__set__(x, z).

    2.a. In the highly unusual case that the search finds a descriptor with __delete__ but no __set__, raise an AttributeError.

  3. Otherwise, set x.__dict__['y'] = z, or raise an AttributeError if x has no __dict__. (This uses the "real" __dict__, bypassing things like mappingproxy.)

This applies to both types and other objects, with the caveats that type.__setattr__ will refuse to set attributes of a class written in C, and type.__setattr__ does some extra internal maintenance you'll never need to worry about unless you do something crazy and unsupported to bypass it.


Post a Comment for "What Is The Lookup Procedure When Setting An Attribute From A Class Or From An Instance?"