Search code examples
pythondecoratorintrospectioninspect

Introspection on a python decorated method


I need to do some introspection on a decorated method in python 2.7. Usually I use getattr(my_module, 'my_method') but the following case returns me the outer function of my decorator.

In my_module.py

def my_decorator(function):
    def outer():
        return function()
    return outer

@my_decorator
def my_method():
    pass

Now in a shell:

>>> import my_module
>>> getattr(my_module, 'my_method')
<function outer at 0x7f46958aa668>

How can I actually get the function that interests me.


Solution

  • You can access the undecorated functon by introspecting the my_method.__closure__ attribute (in Python3) or my_method.func_closure (in Python2):

    def my_decorator(function):
        def outer():
            print('outer')
            return function()
        return outer
    
    @my_decorator
    def my_method():
        print('inner')
    
    try:
        # Python2
        my_method.func_closure[0].cell_contents()
    except AttributeError:
        # Python3
        my_method.__closure__[0].cell_contents()
    

    prints

    inner