Search code examples
pythondecoratorpython-decorators

access to the name of decorator by the decoree


I am decorating a function foo with a_decorator

@a_decorator(params)
def foo(x):
#    print('Called',decorator_name)
#    other magic

Is there a way to access the name a_decorator inside foo so that I can print

'Called a_decorator'

def a_decorator(some_function):
    def wrapper():
        some_function()
        return some_val
    return wrapper

Solution

  • It can be done by attaching decorator name to wrapper function:

    from functools import wraps
    
    def a_decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            val = fn(*args, **kwargs)
            # some action
            return val
    
        wrapper.decorated_by = a_decorator
        return wrapper
    
    @a_decorator
    def foo(x):
        print(x, foo.decorated_by.__name__)
    
    foo('test')  # prints: test a_decorator
    

    Function in python are first class and you can treat them as an object, attach attributes, etc.