Python Proxy Objects: Delegation with `__getattr__`
This article explains how proxy objects forward attribute access in Python with __getattr__ and __setattr__, why special methods, type checks and copies bypass them, and how to build logging and lazy proxies that behave correctly.
A proxy is an object that stands in for another object, receives the operations intended for it and forwards them, adding something along the way: a log entry, a permission check or the postponed creation of an expensive resource. The present article examines how such objects are built in Python with the hooks __getattr__ and __setattr__, and where the illusion breaks: special methods that bypass those hooks, type checks that see through the disguise and copies that send the proxy into infinite recursion. Each limitation is reproduced and corrected with code that runs. An object that intercepts every attribute access without the code that uses it noticing is the secret weapon of this technique.
Forwarding Attribute Access
The method __getattr__ is called only when the normal lookup of an attribute fails, so a proxy that stores the real object and defines __getattr__ forwards every attribute it does not have itself. The method __setattr__, in contrast, is called for every assignment, including those inside __init__, which is why the proxy stores its own data with object.__setattr__.
class LoggingProxy:
def __init__(self, target):
object.__setattr__(self, "_target", target)
def __getattr__(self, name):
print(f"get {name}")
return getattr(self._target, name)
def __setattr__(self, name, value):
print(f"set {name}")
setattr(self._target, name, value)
items = [3, 1, 2]
proxy = LoggingProxy(items)
proxy.append(4) # Output: get append
proxy.sort() # Output: get sort
print(items) # Output: [1, 2, 3, 4]
try:
len(proxy)
except TypeError as error:
print(error) # Output: object of type 'LoggingProxy' has no len()
try:
proxy[0]
except TypeError as error:
print(error) # Output: 'LoggingProxy' object is not subscriptable
The method calls reach the list and are logged, and the list itself changes. The built-in len and the subscription proxy[0], however, fail, because Python looks up special methods such as __len__ and __getitem__ on the class of the object, not through its attributes, a rule described in the article devoted to the data model. Many tutorials claim that indexing a proxy built only with __getattr__ works; it does not, and the same applies to operators, iteration, in, comparisons and with.
Special Methods and Type Checks
A proxy that must behave like a container therefore defines each required special method and forwards it explicitly. Type checks are a second barrier, and a common answer to them is to override __class__, the attribute that isinstance consults.
class ListProxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
return getattr(self._target, name)
def __len__(self):
return len(self._target)
def __getitem__(self, index):
return self._target[index]
def __iter__(self):
return iter(self._target)
def __repr__(self):
return f"ListProxy({self._target!r})"
@property
def __class__(self):
return type(self._target)
proxy = ListProxy([10, 20, 30])
print(len(proxy), proxy[0], list(proxy)) # Output: 3 10 [10, 20, 30]
print(isinstance(proxy, list)) # Output: True
print(type(proxy).__name__) # Output: ListProxy
print(proxy == [10, 20, 30]) # Output: False
With the three forwarded methods, len, indexing and iteration work, and the property __class__ makes isinstance(proxy, list) answer True, the same technique that unittest.mock applies when a mock receives a specification. In the words of a certain hooded knight at a checkpoint, "These aren't the droids you're looking for": the proxy persuades isinstance, but type still reveals the real class, and the comparison with an equal list is False because __eq__ was not forwarded. Tools that read attributes without triggering dynamic lookup, such as inspect.getattr_static, also see the proxy as it is, as described in the article devoted to inspect.
Lazy Initialization
A lazy proxy postpones the creation of an expensive object, such as a database connection, until the first attribute is requested. The following example counts the instances created instead of simulating a delay, so that the moment of creation is visible.
class LazyProxy:
def __init__(self, factory):
object.__setattr__(self, "_factory", factory)
object.__setattr__(self, "_instance", None)
def _resolve(self):
instance = object.__getattribute__(self, "_instance")
if instance is None:
instance = object.__getattribute__(self, "_factory")()
object.__setattr__(self, "_instance", instance)
return instance
def __getattr__(self, name):
return getattr(self._resolve(), name)
def __setattr__(self, name, value):
setattr(self._resolve(), name, value)
created = []
class Connection:
def __init__(self):
created.append(self)
self.status = "active"
def count_users(self):
return 150
connection = LazyProxy(Connection)
print(len(created)) # Output: 0
print(connection.count_users()) # Output: 150
print(connection.status, len(created)) # Output: active 1
connection.status = "closed"
print(created[0].status) # Output: closed
No connection exists after the proxy is built; the first method call creates it, and later accesses reuse the same instance, so the counter stays at one. The assignment through the proxy reaches the real object. The internal attributes are read with object.__getattribute__ and written with object.__setattr__, which keeps them on the proxy and prevents the hooks from calling themselves. If several threads may perform the first access at the same time, _resolve must be protected by a lock, or two connections may be created.
Pitfalls of Proxy Objects
A proxy imitates an object through a set of hooks, and every operation that does not pass through those hooks exposes it. Six pitfalls are distinguished, which are the following:
- Special methods are not forwarded. Operators,
len, indexing, iteration,inandwithignore__getattr__and require explicit methods. - Identity and type.
proxy is targetis always false andtype(proxy)returns the proxy class, even whenisinstancehas been persuaded. - Recursion in the hooks. A
__getattr__or__setattr__that reads or writes the proxy's own attributes through normal syntax can call itself indefinitely. - Copying and unpickling.
copyandpicklecreate the object without calling__init__, so a__getattr__that reads its own storage unconditionally recurses untilRecursionError. - Hidden costs. Every forwarded access adds a Python function call, and a lazy proxy moves the cost of creation to an unpredictable first use.
- Lifetime. A proxy keeps its target alive; when that is not desired,
weakref.proxy, described in the article devoted to weak references, forwards access without owning the object.
The fourth pitfall is reproduced and corrected in the following example.
import copy
class NaiveProxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
return getattr(self._target, name)
try:
copy.copy(NaiveProxy([1, 2]))
except RecursionError:
print("RecursionError") # Output: RecursionError
class SafeProxy(NaiveProxy):
def __getattr__(self, name):
if name == "_target":
raise AttributeError(name)
return getattr(self._target, name)
clone = copy.copy(SafeProxy([1, 2]))
print(clone.count(1)) # Output: 1
The copy is created without __init__, so it has no _target; when copy asks for an optional method, __getattr__ reads self._target, which is missing, and that lookup calls __getattr__ again. Raising AttributeError for the proxy's own storage breaks the cycle, and the copy then works like the original.
Choosing a Delegation Technique
Consequently, a hand-written proxy is justified when the intercepted operations are known and few, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Logging or checking a few known methods | Explicit wrapper methods, without __getattr__ |
| Forwarding an open set of ordinary attributes | __getattr__, with its own storage guarded |
| A proxy that must act as a container or number | __getattr__ plus every required special method |
| Deferring an expensive object | A lazy proxy with a lock, or functools.cached_property on the owner |
| Referencing an object without keeping it alive | weakref.proxy |
| Replacing objects in tests | unittest.mock with spec or autospec |
Conclusion
It is concluded that a proxy in Python is built from __getattr__, which forwards the attributes that the proxy lacks, and __setattr__, which intercepts every assignment, and that the illusion is limited by the lookup of special methods on the type, by type and identity, and by the creation of copies without __init__. This magic is the basis of lazy objects, logging wrappers and test doubles, provided that every operation the proxy must support is forwarded explicitly. Delegation along the hierarchy of a class, instead of to a separate object, is the task of super(), which is developed in a future article of this series.