I\'m looking for way to pass method calls through from an object (wrapper) to a member variable of an object (wrappee). There are potentially many methods that need to be ex
Here's another monkey-patch method. This one copies methods into the Wrapper class directly rather than the created wrapper object. The key advantage to this one is that all special methods such as __add__ will work.
class Wrapper(object):
def __init__(self, wrappee):
self.wrappee = wrappee
def foo(self):
print('foo')
def proxy_wrap(attr):
"This method creates a proxy method that calls the wrappee's method."
def f(self, *args):
return getattr(self.wrappee, attr)(*args)
return f
# Don't overwrite any attributes already present
EXCLUDE = set(dir(Wrapper))
# Watch out for this one...
EXCLUDE.add('__class__')
for (attr, value) in inspect.getmembers(Wrappee, callable):
if attr not in EXCLUDE:
setattr(Wrapper, attr, proxy_wrap(attr))
I used this to wrap numpy arrays. With Wrappee set to np.ndarray:
import numpy as np
Wrappee = np.ndarray
# [The block I wrote above]
wrapped = Wrapper(np.arange(10))
Operations such as wrapped + 1 still work.