I want to create a proxy class that wraps an int
for thread-safe access. In contrast to the built-in type, the proxy class is mutable, so that it can be incremented in-place. Now, I want to use that class just as a normal integer from the outside. Usually, Python's __getattr__
makes it very easy to forward attribute access to the inner object:
class Proxy:
def __init__(self, initial=0):
self._lock = threading.Lock()
self._value = initial
def increment(self):
with self._lock:
self._value += 1
def __getattr__(self, name):
return getattr(self._value, name)
However, __getattr__
does not get triggered for magic methods like __add__
, __rtruediv__
, etc that I need for the proxy to behave like an integer. Is there a way to generate those methods automatically, or otherwise forward them to the wrapped integer object?