I would like to expose the methods of a class as functions (after decoration) in my local scope. For example if I had a class and decorator:
def some_decorator(f):
...transform f...
return decorated_f
class C(object):
def __init__(self,x):
self.x = x
def f(self,y):
"Some doc string"
return self.x + y
def g(self,y,z):
"Some other doc string"
return self.x + y + z
and if I didn't care about automizing the process I could add the following code to my module the following:
@some_decorator
def f(C_instance,x):
"Some doc string."
return C_instance.f(x)
@some_decorator
def g(C_instance,x,y):
"Some other doc string."
return C_instance.g(x,y)
to the effect that the following evaluate to True
c = C(0)
f(c,1) == c.f(1)
But I would like to be able to do this automatically. Something like:
my_funs = expose_methods(MyClass)
for funname, fun in my_funs.iteritems():
locals()[funname] = some_decorator(fun)
foo = MyClass(data)
some_functionality(foo,*args) == foo.some_functionality(*args)
would do the trick (although it feels a little wrong declaring local variables this way). How can I do this in a way so that all the relevant attributes of the method correctly transform into the function versions? I would appreciate any suggestions.
P.S.
I am aware that I can decorate methods of class instances, but this is not really what I am after. It is more about (1) a preference for the function version syntax (2) the fact that my decorators make functions map over collections of objects in fancy and optimized ways. Getting behavior (2) by decorating methods would require my collections classes to inherit attributes from the objects they contain, which is orthogonal to the collection semantics.