← Back to Python, page 5

python-0094 · Hard senior

Implement a lazy-loading proxy with __getattr__, and explain how it differs from __getattribute__.

__getattr__ is called only when normal lookup fails, which makes it safe for proxies and fallbacks. __getattribute__ intercepts every attribute access, including internal ones, so overriding it risks infinite recursion unless it calls object.__getattribute__. A lazy proxy creates the expensive object on first use and forwards attributes to it.

Full answer
python
class LazyClient:
    def __init__(self, factory):
        self._factory = factory
        self._target = None
    def __getattr__(self, name):
        if self._target is None:
            print("connecting...")
            self._target = self._factory()
        return getattr(self._target, name)

class DbClient:
    def query(self, sql):
        return f"rows for {sql!r}"
    timeout = 30

client = LazyClient(DbClient)
print("created proxy")
print(client.query("SELECT 1"))
print(client.timeout, client._target is not None)
try:
    client.missing
except AttributeError as e:
    print("AttributeError:", e)

def __getattr__(name):
    if name == "LEGACY":
        return "deprecated value"
    raise AttributeError(name)
print(__getattr__("LEGACY"))

Output:

text
created proxy
connecting...
rows for 'SELECT 1'
30 True
AttributeError: 'DbClient' object has no attribute 'missing'
deprecated value

Creating the proxy does no work; the first attribute that is not found on the proxy itself triggers the connection, and later accesses reuse the target. _factory and _target are found by normal lookup, so they never reach __getattr__, which is what prevents recursion. Missing attributes on the target raise AttributeError naming the target class. Modules can define a module-level __getattr__ (PEP 562) for lazy imports or deprecation warnings; the last lines show the function directly. A proxy does not forward special methods such as __len__, because Python looks those up on the type.

python
class LazyClient:
    def __init__(self, factory):
        self._factory = factory
        self._target = None
    def __getattr__(self, name):
        if self._target is None:
            print("connecting...")
            self._target = self._factory()
        return getattr(self._target, name)

class DbClient:
    def query(self, sql):
        return f"rows for {sql!r}"
    timeout = 30

client = LazyClient(DbClient)
print("created proxy")
print(client.query("SELECT 1"))
print(client.timeout, client._target is not None)
try:
    client.missing
except AttributeError as e:
    print("AttributeError:", e)

def __getattr__(name):
    if name == "LEGACY":
        return "deprecated value"
    raise AttributeError(name)
print(__getattr__("LEGACY"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • __getattr__ runs only on failed lookups
  • __getattribute__ runs on every access
  • Lazy proxies defer expensive setup
  • Special methods bypass __getattr__
  • Modules support __getattr__

Common mistakes

  • Overriding __getattribute__ and recursing
  • Expecting len() to work through a simple proxy

Follow-ups

  • How would you forward special methods?
  • How does PEP 562 help with lazy imports?

Tips

  • Explain recursion safety