2009-07-26 13 views
10

私は組み込みモジュールを使用していくつかのインスタンスを挿入しているため、デバッグのためにグローバルにアクセスできます。 __builtins__モジュールの問題点は、メインスクリプトでモジュールであり、モジュール内の辞書であるということですが、場合によっては私のスクリプトがメインのスクリプトやモジュールられるように、私はこれをしなければならない。なぜ__builtins__はmoduleとdictの両方ですか?

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

これより短い回避策はありますか?もっと重要なのは、なぜ__builtins__がこのように振る舞うのでしょうか?

ここにこれを表示するスクリプトがあります。

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

はモジュールb.pyを作成します:モジュールa.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

答えて

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

+0

@warvariuc:モジュールは[builtins'](https://docs.python.org/3/library/builtins.html)に名前が変更されました。 –

関連する問題