【发布时间】:2018-08-02 03:55:00
【问题描述】:
所以,我搞砸了并创建了这个伪状态机应用程序排序模式https://github.com/rebelclause/python_legs/blob/master/init_subclass_example.py 大大扩展了这个回溯方法: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
现在,我意识到这可能不是制作装饰器的正确方法;毕竟回溯必须立即跟随您想要获取其调用者名称的函数。无论如何,我试着知道这一点,但现在乐趣结束了。 我不确定我将如何使用它(即使在我提供的框架中),但有人可以回答如何改进装饰器和捕获调用者姓名的代码,以便它可以作为装饰器工作在一堆装饰器中?也许怎么做?
编辑:在避免协程问题的同时添加了这个...
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?
【问题讨论】:
-
我不确定你在这里问什么。但通常,装饰器的包装器函数将使用传入的 args(或它们的某些转换版本)在某处调用包装函数并返回其结果(可能已转换)。你的只是返回一些它从函数调用者的堆栈框架中提取的字符串,而没有调用它,所以很难看出你如何有效地用任何堆叠在它上面的东西来组合它。
-
您可以按原样使用它,而无需更改类方法上的回溯索引 (-2),并且它会返回调用者,但是,出于某种原因,我没有深入研究,它不会运行该方法的代码。
-
我写了一个答案,解释如何让它运行该方法的代码——但如果这是您的实际问题,请编辑问题以说明这一点,而不是将其留在评论中。同时,我仍然不知道您要在这里提取和打印什么,但我做了一些猜测并将其添加到答案中。
标签: python state decorator callable