I am trying to build a control structure in a class method that takes a function as input and has different behaviors if a function is decorated or not. Any ideas on how you would go about building a function is_decorated
that behaves as follows:
def dec(fun):
# do decoration
def func(data):
# do stuff
@dec
def func2(data):
# do other stuff
def is_decorated(func):
# return True if func has decorator, otherwise False
is_decorated(func) # False
is_decorated(func2) # True
Yes, it's relatively easy because functions can have arbitrary attributes added to them, so the decorator function can add one when it does its thing:
def dec(fun):
def wrapped(*args, **kwargs):
pass
wrapped.i_am_wrapped = True
return wrapped
def func(data):
... # do stuff
@dec
def func2(data):
... # do other stuff
def is_decorated(func):
return getattr(func, 'i_am_wrapped', False)
print(is_decorated(func)) # -> False
print(is_decorated(func2)) # -> True