Determining if a function is a method of a class within a decorator
davidh at ilm.com
Mon Jun 29 21:01:29 EDT 2009
I'm having a little problem with some python metaprogramming. I want to
have a decorator which I can use either with functions or methods of
classes, which will allow me to swap one function or method for another.
It works as I want it to, except that I want to be able to do some
things a little differently depending on whether I'm swapping two
functions, or two methods of a class.
Trouble is, it appears that when the decorator is called the function is
not yet bound to an instance, so no matter whether it's a method or
function, it looks the same to the decorator.
This simple example illustrates the problem:
def __init__(self, replacement):
self.replacement = replacement
def __call__(self, thingToReplace):
def _replacer(*args, **kws):
return self.replacement(*args, **kws)
print "this method will be swapped in"
print "this method will be swapped out"
c = MyClass()
print "this function will be swapped in"
print "this function will be swapped out"
Both MyClass.swapIn and swapInFn look like the same thing to the
decorator, and MyClass.swapOut and swapOutFn look the same. So is there
a pattern I can follow that will allow me to determine whether the
objects I'm given are plain functions or belong to a class?
Thanks in advance,
More information about the Python-list