Skip to the solution
HardDSA9 min read

What is the difference between __getattr__ and __getattribute__?

407 views

The problem

Question presented to candidate: "Python classes can define both __getattr__ and __getattribute__. What is the difference, when does each one run, and which would you use to build something like a proxy or a lazy-loading object?"

What a strong answer should cover:

  • __getattribute__ is called for every attribute read on an instance (including methods and __dict__); object.__getattribute__ implements the normal lookup.
  • __getattr__ is a fallback, called only when the normal lookup raises AttributeError; the normal case pays nothing for it.
  • The recursion trap: any self.x inside __getattribute__ calls it again; use object.__getattribute__(self, name) or super().__getattribute__(name).
  • Both must raise AttributeError for unknown names so hasattr and getattr(obj, name, default) keep working; an AttributeError escaping a property silently triggers __getattr__.
  • Implicit special-method lookups (len(x), x + y) bypass both on the instance, so a proxy must define the dunders it needs; modules can define __getattr__ too (PEP 562, Python 3.7).
  • Choice: __getattr__ for delegation, defaults and lazy attributes; __getattribute__ only for rare cases that must see every access (tracing, access control), because it is slower and easy to get wrong.

Code / implementation expected: Optional β€” a delegating proxy with __getattr__, or a tracing __getattribute__ that calls object.__getattribute__.

  • attributes
  • dunder

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWhich hook runs when, the recursion trap and hidden AttributeErrors
PythonA delegating proxy, the dunder bypass and module-level __getattr__

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 132 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How does attribute lookup work on a Python object?

Continue