2009-07-26 71 views
10

我正在使用內置模塊來插入一些實例,因此它們可以被全局訪問用於調試目的。與__builtins__模塊的問題是,它是在一個主腳本模塊,並在模塊的字典,而是取決於不同的情況我的腳本可以是主腳本或模塊,我必須這樣做:爲什麼__builtins__既是模塊又是字典

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

是否有解決方法,比這更短?更重要的是,爲什麼__builtins__這樣表現?

這是看到這個腳本。創建一個模塊a.py:

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

創建一個模塊b.py:

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

現在運行python a.py:

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

欲瞭解更多信息,請參閱http://stackoverflow.com/questions/11181519/python-whats-the-difference-between-builtin-and-builtins [可能重複] – pd12 2015-08-11 05:24:37

回答

11

我想你想的__builtin__模塊(注意單數)。

請參閱該文檔:

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.

+0

Python3呢? `NameError:name'__builtin__'未定義# – warvariuc 2014-03-03 06:28:07