Python: can a decorator determine if a function is being defined inside a class?

前端 未结 6 860
Happy的楠姐
Happy的楠姐 2021-02-07 11:58

I\'m writing a decorator, and for various annoying reasons[0] it would be expedient to check if the function it is wrapping is being defined stand-alone or as part of a class (a

6条回答
  •  广开言路
    2021-02-07 12:54

    I think the functions in the inspect module will do what you want, particularly isfunction and ismethod:

    >>> import inspect
    >>> def foo(): pass
    ... 
    >>> inspect.isfunction(foo)
    True
    >>> inspect.ismethod(foo)
    False
    >>> class C(object):
    ...     def foo(self):
    ...             pass
    ... 
    >>> inspect.isfunction(C.foo)
    False
    >>> inspect.ismethod(C.foo)
    True
    >>> inspect.isfunction(C().foo)
    False
    >>> inspect.ismethod(C().foo)
    True
    

    You can then follow the Types and Members table to access the function inside the bound or unbound method:

    >>> C.foo.im_func
    
    >>> inspect.isfunction(C.foo.im_func)
    True
    >>> inspect.ismethod(C.foo.im_func)
    False
    

提交回复
热议问题