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

Terry Reedy tjreedy at
Mon Jun 29 21:31:45 EDT 2009

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.

Unbounds methods are simply functions which have become attributes of a 
class. Especially in Py3, there is *no* difference.

Bound methods are a special type of partial function. In Python, both 
are something else, though still callables.  Conceptually, a partial 
function *is* a function, just with fewer parameters.

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

Right. Whether it is an A or an A, it looks like an A.

Worse: when the decorator is called, there is no class for there to be 
instances of.
> This simple example illustrates the problem:

Add a second parameter to tell the decorator which variant of behavior 
you want. Or write two variations of the decorator and use the one you want.


More information about the Python-list mailing list