【问题标题】:Access the locals available in the previous stack frame访问上一个堆栈帧中可用的局部变量
【发布时间】: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


【解决方案1】:

框架对象位于您定义的“框架”变量中。要获取框架对象的局部变量,您可以像这样调用其 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'>}

【讨论】:

  • 太棒了。将对其进行调查,看看这是否适用于一般情况,然后接受:)
  • 谢谢。我昨天确实试过f_locals,但一定是把自己和双重frameframe.frame)搞混了。我可能做过frame.f_locals XD。
猜你喜欢
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
相关资源
最近更新 更多