0

How can I identify if the current function being decorated is a method (belonging to a class) or a function?

class ClassA:
  @mydecorator
    def method(self)
    pass

  @staticmethod

@mydecorator
def function()
  pass

mydecorator need to know if the decorated function is:

  • a method (is_method)
  • a static method (is_static)
  • a class method (is_classmethod)
  • a global function (is_function)

How can we do this?

Thanks!

Gaetan
  • 488
  • 4
  • 13
  • When the decorator is applied, the function is still a function; the method is bound only when accessed from the class (dynamically, each time). – Martijn Pieters Sep 04 '13 at 09:34

1 Answers1

0
is_method = lambda f: hasattr(f, 'im_self')

is_static = lambda f: isinstance(f, types.FunctionType)

is_classmethod = lambda f: getattr(f, 'im_self', None) is not None

is_function = lambda f: not hasattr(f, 'im_self')

http://docs.python.org/2/reference/datamodel.html#types

tuxcanfly
  • 2,494
  • 1
  • 20
  • 18
  • This doesn't work on instance on the method (f should be equal to ClassA.method but here we have ClassA().method()) – Gaetan Sep 04 '13 at 11:28