Skip to content

[3.9] Improve discussion about how __getattr__ is invoked. (GH-31435) #31438

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 20, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions Doc/howto/descriptor.rst
Original file line number Diff line number Diff line change
Expand Up @@ -696,10 +696,14 @@ a pure Python equivalent:
>>> b.g == b['g'] == ('getattr_hook', b, 'g')
True

Note, there is no :meth:`__getattr__` hook in the :meth:`__getattribute__`
code. That is why calling :meth:`__getattribute__` directly or with
``super().__getattribute__`` will bypass :meth:`__getattr__` entirely.

Interestingly, attribute lookup doesn't call :meth:`object.__getattribute__`
directly. Instead, both the dot operator and the :func:`getattr` function
perform attribute lookup by way of a helper function:
Instead, it is the dot operator and the :func:`getattr` function that are
responsible for invoking :meth:`__getattr__` whenever :meth:`__getattribute__`
raises an :exc:`AttributeError`. Their logic is encapsulated in a helper
function:

.. testcode::

Expand Down Expand Up @@ -744,12 +748,6 @@ perform attribute lookup by way of a helper function:
...
AttributeError: 'ClassWithoutGetAttr' object has no attribute 'z'

So if :meth:`__getattr__` exists, it is called whenever :meth:`__getattribute__`
raises :exc:`AttributeError` (either directly or in one of the descriptor calls).

Also, if a user calls :meth:`object.__getattribute__` directly, the
:meth:`__getattr__` hook is bypassed entirely.


Invocation from a class
-----------------------
Expand Down