简体   繁体   English

为什么 __builtins__ 既是模块又是字典

[英]why __builtins__ is both module and dict

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: __builtins__模块的问题在于它是主脚本中的一个模块并且是模块中的一个字典,但是由于我的脚本取决于案例可以是主脚本或模块,我必须这样做:

if isinstance(__builtins__, dict):
    __builtins__['g_frame'] = 'xxx'
else:
    setattr(__builtins__, 'g_frame', 'xxx')

Is there a workaround, shorter than this?有没有比这更短的解决方法? More importantly, why does __builtins__ behave this way?更重要的是,为什么__builtins__会这样?

Here is a script to see this.这是一个用于查看此内容的脚本。 Create a module a.py:创建模块a.py:

#module-a
import b
print 'a-builtin:',type(__builtins__)

Create a module b.py:创建模块 b.py:

#module-b
print 'b-builtin:',type(__builtins__)

Now run python a.py:现在运行 python a.py:

$ python a.py 
b-builtin: <type 'dict'>
a-builtin: <type 'module'>

I think you want the __builtin__ module (note the singular).我想你想要__builtin__模块(注意单数)。

See the docs:请参阅文档:

27.3. 27.3。 __builtin__ — Built-in objects __builtin__ — 内置对象

CPython implementation detail: Most modules have the name __builtins__ (note the 's' ) made available as part of their globals. CPython 实现细节:大多数模块的名称__builtins__ (注意's' )作为其全局变量的一部分可用。 The value of __builtins__ is normally either this module or the value of this modules's [sic] __dict__ attribute. __builtins__的值通常是此模块或此模块的 [sic] __dict__属性的值。 Since this is an implementation detail, it may not be used by alternate implementations of Python.由于这是一个实现细节,它可能不会被 Python 的替代实现使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM