访问上一个堆栈框架中可用的本地文件

问题描述 投票:1回答:1

我有一个调试上下文管理器,我想在启动上下文管理器时访问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"
python inspect contextmanager
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.