【问题标题】:Getting a variable from the caller's globals. What is a frame object?从调用者的全局变量中获取变量。什么是框架对象?
【发布时间】:2023-04-06 03:59:01
【问题描述】:

inspect module 的文档说:

当以下函数返回“帧记录”时,每条记录都是一个 命名元组FrameInfo(frame, filename, lineno, function, code_context, index)。元组包含框架对象、文件名、行 当前行号,函数名,行列表 源代码中的上下文,以及当前行的索引 那个列表。

究竟什么是“框架对象”?我希望使用这个框架对象从调用者的globals() 中获取变量的值:

import my_util

a=3
my_util.get_var('a')

和 my_util.py

import inspect

def get_var(name):
    print(inspect.stack()[1][0])

【问题讨论】:

  • 虽然文档没有解释框架对象实际上是什么,但他们至少在this table 中描述了它的结构(向下滚动到“框架”)。看起来你可以做return inspect.stack()[1][0].f_globals[name]。
  • @Rawing 谢谢,这似乎有效!
  • 一个小补充,如果你想深入一点,我发现这个 SO 线程非常有用 - stackoverflow.com/questions/23848391/…

标签: python introspection


【解决方案1】:

来自https://docs.python.org/3/library/inspect.html#types-and-members:

frame   f_back      next outer frame object (this frame’s caller)
        f_builtins  builtins namespace seen by this frame
        f_code      code object being executed in this frame
        f_globals   global namespace seen by this frame
        f_lasti     index of last attempted instruction in bytecode
        f_lineno    current line number in Python source code
        f_locals    local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace     tracing function for this frame, or None

因此要在 my_util.py 中获取一些全局变量:

import inspect

def get_var(name):
    print(inspect.stack()[1][0].f_globals[name])

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2013-05-06
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多