Why do data descriptors (e.g. properties) take priority over instance attributes?

dieter dieter at handshake.de
Tue Dec 18 03:54:48 EST 2018


Paul Baker <paulbaker8 at gmail.com> writes:
> When Python looks up an attribute on an object (i.e. when it executes
> `o.a`), it uses an interesting priority order [1]. It looks for:
>
>  1. A class attribute that is a data-descriptor (most commonly a property)
>  2. An instance attribute
>  3. Any other class attribute
> ...
> Why does Python use this priority order rather than the "naive" order
> (instance attributes take priority over all class attributes, as used
> by JavaScript)? Python's priority order has a significant drawback: it
> makes attribute lookups slower, because instead of just returning an
> attribute of `o` if it exists (a common case), Python must first
> search `o`'s class *and all its superclasses* for a data-descriptor.
>
> What is the benefit of Python's priority order? It's presumably not
> just for the above situation, because having an instance variable and
> a property of the same name is very much a corner case (note the need
> to use `self.__dict__['a'] = 1` to create the instance attribute,
> because the usual `self.a = 1` would invoke the property).
>
> Is there a different situation in which the "naive" lookup order would
> cause a problem?

"special methods" are looked up in the same way - at least when
called indirectly. There is a section in the "library reference"
explaining why this special lookup is used in this case.
In old Python versions, "special methods" have been looked up in the normal
way; changing the lookup has been a major incompatibility. Thus,
apparently, there have been good reasons for the change.




More information about the Python-list mailing list