Determining if a function is a method of a class within a decorator

Steven D'Aprano steven at
Mon Jun 29 22:25:24 EDT 2009

On Mon, 29 Jun 2009 18:01:29 -0700, David Hirschfield wrote:

> 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.


* use a naming convention to recognise methods (e.g. check if the first 
argument is called "self" by looking at function.func_code.co_varnames);

* use two different decorators, or a decorator that takes an extra 
"method or function argument";

* play around with the class metaclass and see if you can do something 
special (and probably fragile);

* do the replacements after the class is created without decorator 
syntax, e.g.:

Class.method1 = swapWith(Class.method2)(Class.method1)

> This simple example illustrates the problem:

No it doesn't. It appears to work perfectly, from what I can guess you're 
trying to accomplish.

Have you considered a possibly simpler way of swapping methods/functions?

>>> def parrot():
...     print "It's pining for the fjords."
>>> def cheeseshop():
...     print "We don't stock Cheddar."
>>> parrot, cheeseshop = cheeseshop, parrot
>>> parrot()
We don't stock Cheddar.
>>> cheeseshop()
It's pining for the fjords.

Admittedly, this doesn't let you do extra processing before calling the 
swapped functions, but perhaps it will do for what you need.


More information about the Python-list mailing list