2009-07-26 3 views
10

Ich benutze das eingebaute Modul, um ein paar Instanzen einzufügen, so dass sie global für Debugging-Zwecke zugegriffen werden können. Das Problem mit dem __builtins__ Modul ist, dass es sich um ein Modul in einem Hauptskript und ist ein dict in Module, aber als mein Skript über Fälle je kann ein Hauptskript oder ein Modul sein, ich habe dies zu tun:Warum __builtins__ ist Modul und dict

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

Gibt es einen Workaround, kürzer als das? Noch wichtiger, warum verhält sich __builtins__ so?

Hier ist ein Skript, um dies zu sehen. Erstellen Sie ein Modul a.py:

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

Erstellen Sie ein Modul b.py:

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

Jetzt laufen Python a.py:

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

Weitere Informationen finden Sie http://stackoverflow.com/questions/11181519/python-whats-the-difference-between-builtin-and-builtins [Mögliche Duplikate] – pd12

Antwort

11

Ich glaube, Sie wollen das __builtin__ Modul (beachte die Einzahl).

Lesen Sie die Dokumentation:

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

Was ist mit Python3? 'NameError: Name '__builtin__' ist nicht definiert ' – warvariuc

+0

@warvariu: Das Modul wurde umbenannt in [' builtins'] (https://docs.python.org/3/library/builtins.html). –

Verwandte Themen