gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:42:07 25 4
gpt4 key购买 nike

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.

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

关于python - 从调用者的全局变量中获取变量。什么是框架对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com