ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 全局帧与堆栈帧

2019-08-24 02:07:54  阅读:526  来源: 互联网

标签:python python-2-7 stack stack-trace global


以下所有内容均来自www.pythontutor.com的主页(顺便提一下,这是一个很棒的工具和网站).

这是some code

Here's some code:

以下是作者在上述代码的当前执行点描述的“全局框架”和“堆栈框架”:

Here's what the author describes as the "global frame" and the "stack frames" at the current point of execution for the above code

我的问题:“全局框架”和“堆栈框架”之间有什么区别?这个术语是否正确(我用Google搜索并得到各种不同的答案)?

解决方法:

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

当你调用一个函数(用python源代码定义)时,它会为它的本地执行添加一个框架到堆栈,当一个模块被加载时,一个框架将全局执行模块添加到堆栈中.

框架没有任何标准化的命名约定,因此互联网上的术语可能会相互矛盾.通常,您可以通过文件和函数名称来识别它们. Python将全局帧称为名为< module>的函数.从上面的例子(function =’< module>‘)或错误中可以看出:

>>> raise TypeError
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    raise TypeError               # ^ up there
TypeError

“全局”和“功能”框架之间唯一真正的区别是,对于全局框架,全局和局部变量之间没有区别:

>>> my_frame.f_globals is my_frame.f_locals
True

这就是为什么将global关键字放在全局框架中是没有意义的,它表示变量名称 – 在分配时 – 应该放在.f_globals而不是.f_locals中.但除此之外,所有帧都非常相同.

标签:python,python-2-7,stack,stack-trace,global
来源: https://codeday.me/bug/20190824/1703510.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有