I’m trying to write a wrapper for an external module in python. The module provides a method to conjugate a verb that expects 2 arguments. I would like to wrap it into several methods and I was wondering if there was a way to do it programatically.
i.e. instead of:
class X:
def a(self,arg):
return module.do(arg,'a')
def b(self,arg):
return module.do(arg,'b')
...
def z(self,arg):
return module.do(arg,'z')
I was trying to do:
class X:
def a(self,arg):
return module.do(arg,__name__)
return module.do(arg,__name__)
def __init__(self):
setattr(self,'b',self.a)
...
setattr(self,'z',self.a)
x = X()
x.a(y)
x.b(y)
x.z(y)
The problem is that name returns the top level method, not the current.
I tried both:
from inspect import stack
stack()[0][3]
import sys
sys._getframe().f_code.co_name
But when I call b() or z() I get ‘a’.
Am I doing something wrong? Is there any other way to achieve a similar result?
You’re simply setting all the
btozattributes of your class to point to theamethod. This means that whenever somebody accessesinstance.b, it gives back theamethod (which is why theco_nameis alwaysa).You can accomplish what you want like this: