why __builtins__ is both module and dict

岁酱吖の 提交于 2019-11-30 08:11:35

问题


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

回答1:


I think you want the __builtin__ module (note the singular).

See the docs:

27.3. __builtin__ — Built-in objects

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.



来源:https://stackoverflow.com/questions/1184016/why-builtins-is-both-module-and-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!