Peteris :
I'm trying to "wrap" an existing classmethod, i.e.,
def Foo:
@classmethod
def bar(cls, x): return x + 2
old_bar = Foo.bar
def wrapped_bar(cls, x):
result = old_bar(cls, x) # Results in an error
return result
Foo.bar = wrapped_bar
It seems that Foo.bar
is already bound with cls = Foo
, how do I get the unbound version of the function bar
?
[I'm not allowed to modify Foo
, it exists in another codebase that I'm patching]
juanpa.arrivillaga :
Suppose, you have:
>>> class Foo:
... @classmethod
... def bar(cls, x):
... return x*42
...
>>> Foo.bar(2)
84
Then one way is to access the name-space of your class directly. Then you should be able to access the classmethod
object and obtain the decorated function available at the __func__
attribute:
>>> vars(Foo)['bar']
<classmethod object at 0x103eec520>
>>> vars(Foo)['bar'].__func__
<function Foo.bar at 0x1043e49d0>
Alternatively, it is accessible on the bound-method object itself:
>>> bound = Foo.bar
>>> bound
<bound method Foo.bar of <class '__main__.Foo'>>
>>> bound.__func__
<function Foo.bar at 0x1043e49d0>