I want to write a decorator that can be applied to single functions and to functions that are nested within objects. The difficulty is that I want the decorator to access object variables (via self.var) or function variables (via kwargs).
My sample code to decorate a single function looks like:
def outer_decorator(var_to_print):
def inner_decorator(function):
def wrapper(*args, **kwargs):
if var_to_print in kwargs.keys():
string_to_print = kwargs.get(var_to_print, "")
print(string_to_print)
return function(*args, **kwargs)
return wrapper
return inner_decorator
@outer_decorator(var_to_print='var')
def print_something(var=''):
print('print_second')
print_something(var = 'print_first')
#print_first
#print_second
For objects I want to do something similar but instead of accessing kwargs, I would like to access self.var:
def wrapper(self, *args, **kwargs):
string_to_print = getattr(self, var_to_print)
print(string_to_print)
return function(self, *args, **kwargs)
Any ideas on how to check dynamically what wrapper should be applied? I tried to check whether it is a callable, but that seems to apply to both.
callable(var_to_print)and it gives meFalseas I would expect...callable(normal_function)andcallable(function_of_object)evaluate to true, which they both do