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

David Hirschfield davidh at
Mon Jun 29 22:01:01 EDT 2009

Yeah, it definitely seems like having two separate decorators is the 
solution. But the strange thing is that I found this snippet after some 
deep googling, that seems to do something *like* what I want, though I 
don't understand the descriptor stuff nearly well enough to get what's 

answer number 3, by ianb. It seems to indicate there's a way to 
introspect and determine the class that the function is going to be 
bound to...but I don't get it, and I'm not sure it's applicable to my case.

I'd love an explanation of what is going on in that setup, and if it 
isn't usable for my situation, why not?
Thanks again,

Terry Reedy wrote:
> 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.
> tjr

mediocre nebula.

More information about the Python-list mailing list