在此处,作者描述的是上述代码当前执行点的“全局帧”和“堆栈帧”:
我的问题:
“全局框架”和“堆栈帧”有什么区别?这个术语是否正确(我四处搜索并得到了各种不同的答案)? 当您调用功能时,为本地执行创建了一个帧。加载模块时,为全局模块执行创建了一个帧。
PythonTutor不支持显示跨多个文件执行的执行,因此主模块的初始帧似乎是独一无二的,但是您可以想象该语句import foo
frames
是您可以与之交互的实际Python对象:
import inspect
my_frame = inspect.currentframe()
print(my_frame) #<frame object at MEMORY_LOCATION>
print(my_frame.f_lineno) #this is line 7 so it prints 7
print(my_frame.f_code.co_filename) #filename of this code executing or '<pyshell#1>' etc.
print(my_frame.f_lineno) #this is line 9 so it prints 9
全局框架与本地框架没有什么特别的特殊之处 - 它们只是执行的框架:
stack
当您调用一个函数(用Python源代码定义)时,它将为堆栈添加一个本地执行的帧,而当将模块加载到帧中时,将模块的全局执行添加到堆栈中。
Frames-作为内部数据结构 - 没有规范的命名约定,因此互联网上的术语可能会矛盾。 通常,您可以通过文件和函数名称识别它们。 Python将全局帧称为称为名为Python 3.6.0a1 (v3.6.0a1:5896da372fb0, May 16 2016, 15:20:48)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> import pprint
>>> def test():
... pprint.pprint(inspect.stack())
...
>>> test() #shows the frame in test() and global frame
[FrameInfo(frame=<frame object at 0x1003a3be0>, filename='<stdin>', lineno=2, function='test', code_context=None, index=None),
FrameInfo(frame=<frame object at 0x101574048>, filename='<stdin>', lineno=1, function='<module>', code_context=None, index=None)]
>>> pprint.pprint(inspect.stack()) #only shows global frame
[FrameInfo(frame=<frame object at 0x1004296a8>, filename='<stdin>', lineno=1, function='<module>', code_context=None, index=None)]
的函数,如上所述(
<module>
)或错误中所示:
function='<module>'
全球框架全局和局部变量之间没有区别:
>>> raise TypeError
Traceback (most recent call last): # v v
File "<pyshell#4>", line 1, in <module> # <<<
raise TypeError # ^ ^ ^ ^
TypeError
这就是为什么将
>>> my_frame.f_globals is my_frame.f_locals
True
关键字放在全局帧中毫无意义的原因,它指示了可变名称 - 分配时应将其放入
global
而不是.f_globals
中。 但其他所有框架几乎相等。