00__00__00
00__00__00

Reputation: 5327

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

Upvotes: 1

Views: 44

Answers (1)

Gennady Kandaurov
Gennady Kandaurov

Reputation: 1964

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.

Upvotes: 2

Related Questions