我有一个调试上下文管理器,我想在启动上下文管理器时访问locals(),而不将本地作为参数。这可能吗?
我想在一般情况下这样做,以便可以从任何导入Debug
的文件中使用我的Debug上下文管理器,而不仅仅是在下面的tinkertoy示例中。
这是我的最小例子:
import inspect
class Debug:
def __init__(self):
frames = inspect.stack()
for frame in frames:
line = frame.code_context[0]
if "Debug" in line:
break
# I want to get the locals() at the time debug was called here!
# give me i_will_be_in_the_locals
raise Exception()
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
if __name__ == "__main__":
i_will_be_in_the_locals = 42
with Debug():
"hi"