访问前一个栈帧中可用的局部变量

Access the locals available in the previous stack frame

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

框架对象在您定义的 "frame" 变量中。要获取框架对象的局部变量,您可以这样调用其 f_locals 属性:

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"

返回值为:

{'Debug': <class '__main__.Debug'>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__cached__': None,
 '__doc__': None,
 '__file__': '/home/user1/main-projects/overflow/file.py',
 '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f7bbb44f7f0>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'i_will_be_in_the_locals': 42,
 'inspect': <module 'inspect' from '/usr/lib/python3.5/inspect.py'>}