1

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 
3
  • 1
    How is a_decorator defined? Commented Mar 6, 2018 at 19:31
  • 2
    In general, no. Doing so would require a lot of explicit namespace wrangling by the decorator itself. Commented Mar 6, 2018 at 19:58
  • can be an answer for me Commented Mar 6, 2018 at 20:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

great thanks. should it not be wrapper.decorated_by = a_decorator.__name__ ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.