【发布时间】:2019-04-15 22:34:50
【问题描述】:
我有一个调试上下文管理器,我想在启动上下文管理器时访问 locals(),而不将 locals 作为参数。这可能吗?
我想在一般情况下执行此操作,以便可以从导入 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"
【问题讨论】:
-
你已经尝试过的有什么问题,?以上是完整代码吗?
-
我想访问调用 Debug() 的 locals() 现在抛出异常的地方。为此,您需要以某种方式使用 insepect,我敢肯定,但我一直无法弄清楚如何。
标签: python inspect contextmanager