为什么__builtins__是两个模块和快译通(why __builtins__ is both

2019-06-26 19:45发布

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

Is there a workaround, shorter than this? More importantly, why does __builtins__ behave this way?

Here is a script to see this. Create a module a.py:

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

Create a module b.py:

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

Now run python a.py:

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

Answer 1:

我想你想的__builtin__模块(注意单数)。

请参阅该文档:

27.3。 __builtin__ -内置对象

CPython的实现细节:大多数模块具有名称__builtins__ (注意's' )作为全局的一部分提供。 的值__builtins__通常要么是该模块或该模块的[原文如此]的值__dict__属性。 由于这是一个实现细节,它可以不被被Python的替代实施方式中使用。



文章来源: why __builtins__ is both module and dict