I've got the following problem:
I need to write a decorator that would be able to detect a situation where it is used around a method and around a regular function.
So let's consider the following code:
def somedecorator(fn):
print "decorating function:", fn
print "function class:", fn.__class__
return fn
@somedecorator
def regular_func():
print "I'm a regular function"
class SomeClass(object):
@somedecorator
def class_method(self):
print "I'm a class method"
The output reads:
decorating function: <function regular_func at 0x181d398>
function class: <type 'function'>
decorating function: <function class_method at 0x181d410>
function class: <type 'function'>
However writing:
print regular_func
print SomeClass.class_method
print SomeClass().class_method
Produces output:
<function regular_func at 0x181d398>
<unbound method SomeClass.class_method>
<bound method SomeClass.class_method of <__main__.SomeClass object at 0x16d9e50>>
So as it turns out (not so surprisingly) that decorators are applied to functions before they are turned into methods.
Question: What would you suggest to distinguish the two applications from the decorator point of view?
EDIT For the curious ones - I need the described distinction because of pickling. I don't really want to go into details on this one.