为什么__builtins__既是模块又是字典 [英] why __builtins__ is both module and dict
问题描述
我正在使用内置模块插入一些实例,因此可以出于调试目的对其进行全局访问。 __ builtins __
模块的问题在于,它是主脚本中的模块,并且是模块中的字典,但由于我的脚本(视情况而定)可以是主脚本或模块,我必须这样做:
I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the __builtins__
module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this:
if isinstance(__builtins__, dict):
__builtins__['g_frame'] = 'xxx'
else:
setattr(__builtins__, 'g_frame', 'xxx')
有没有比这更短的解决方法?更重要的是,为什么 __ builtins __
会这样?
Is there a workaround, shorter than this? More importantly, why does __builtins__
behave this way?
下面是一个脚本,可以用来查看此内容。创建一个模块a.py:
Here is a script to see this. Create a module a.py:
#module-a
import b
print 'a-builtin:',type(__builtins__)
创建模块b.py:
#module-b
print 'b-builtin:',type(__builtins__)
现在运行python a.py:
Now run python a.py:
$ python a.py
b-builtin: <type 'dict'>
a-builtin: <type 'module'>
推荐答案
我认为您想要 __builtin __
模块(请注意单数形式)。
I think you want the __builtin__
module (note the singular).
查看文档:
27.3.
__builtin__
— Built-in objects
CPython实现细节:大多数模块的名称均为 __ builtins __
(请注意的)作为其全局变量的一部分提供。
__ builtins __
的值通常是此模块或该模块的[sic] __ dict __
的值。 strong>属性。由于这是一个实现细节,因此它可能无法用于Python的其他实现。
CPython implementation detail: Most modules have the name __builtins__
(note the 's'
) made available as part of their globals. The value of __builtins__
is normally either this module or the value of this modules’s [sic] __dict__
attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
这篇关于为什么__builtins__既是模块又是字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!