gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:01:52 28 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 访问前一个堆栈帧中可用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698126/

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