So, I'm messing around and created this pseudo State-Machine app sequencing pattern https://github.com/rebelclause/python_legs/blob/master/init_subclass_example.py extending this traceback method by a wide margin: https://stackoverflow.com/a/1690751/7955763
import traceback # for callable name
from functools import wraps
def tracename(orig_func):
@wraps(orig_func)
def wrapper(*args, **kwargs):
(filename,line_number,function_name,text)=traceback.extract_stack()[-2]
def_name = text[:text.find('=')].strip()
print(def_name)
return def_name
return wrapper
Now, I realize it may not be the right method for the job of making a decorator; after all the traceback has to immediately follow the function whose caller name you want to get. I tried knowing this anyway, but now the fun is over. I'm not sure how I'd use it (even in the framework I've presented), but can someone answer as to how the decorator and the code to capture the caller name can be improved so it'll work as a decorator in a stack of decorators? And maybe how?
Edit: Added this while avoiding a coroutine problem...
import traceback # for callable name
from functools import wraps
# this should make you laugh, or not
def tracename(orig_func):
@wraps(orig_func)
def wrapper(*args, **kwargs):
(filename,line_number,function_name,text)=traceback.extract_stack()[-2]
def_name = text[:text.find('=')].strip()
# print(def_name)
return def_name
return wrapper
class foo(object):
''' '''
def __init__(self):
pass
@tracename
def _goodbye(self):
print("It's been a good run so far, but this decorator might be toast.")
print(foo()._goodbye()) # prints wrapper returned var def_name
foo()._goodbye() # sits and watches while we patiently wait?
# uncomment the print statement in the decorator, then re-run
# then comment out the decorator and run it
guess_who = foo()._goodbye()
print('Guess where def_name went :', guess_who) # would it freak you out if the comment printed, too?