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

时间:2019-04-15 22:34:51

标签: python inspect contextmanager

我有一个调试上下文管理器,我想在启动上下文管理器时访问locals(),而不必将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"

1 个答案:

答案 0 :(得分:1)

frame对象位于您定义的“ frame”变量内。要获取框架对象的局部变量,可以这样调用其f_locals属性:

--prod

返回值是:

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
        from pprint import pprint
        pprint(frame.frame.f_locals)

    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"