从调用者的全局变量中获取变量。什么是框架对象?

Getting a variable from the caller's globals. What is a frame object?

inspect module 的文档说:

When the following functions return “frame records,” each record is a named tuple FrameInfo(frame, filename, lineno, function, code_context, index). The tuple contains the frame object, the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list.

什么是 "frame object"?我希望使用这个框架对象从调用者的 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])

来自 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])