In python 3.7 or more.
I have a the following class:
def dec(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
print("wrapped")
return method(*args, **kwargs)
return wrapper
class A:
@dec()
def f1(self):
print(is_wrapped())
def f2(self):
print(is_wrapped())
I want A().f1()
to print True
and A().f2()
to print False.
I’ve noticed that in the stack frame of the caller of the f1 (i.e, wrapped) the last element in f_locals is always the function that is being wrapped so I created the following code for is_wrapped
:
def is_wrapped():
frame = inspect.currentframe().f_back
caller = frame.f_back
if len(caller.f_locals) > 0:
last_elem = next(reversed(frame.f_back.f_locals.values()))
if hasattr(last_elem, '__code__'):
return last_elem.__code__ is frame.f_code
return False
While this seems to work I don’t know if I can assume that is always the case.
I can make it more robust by checking the code of any element in frame.f_back.f_locals.values() but if I can assume it’s always the last element I rather do it because I want it to do the least amount of operations/checks it needs to do.
If this is not always the case when does it fail?