__builtins__ confusion...

Allan Crooks googlegroups at sixtyten.org
Sat May 11 13:31:08 EDT 2002


Hi,

I just have a question regarding __builtins__. Rather than ask it
outright, I'll just show you what I tried in my interpreter, and then
ask the question.

Fire up Python...

   Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on
win32
   Type "help", "copyright", "credits" or "license" for more
information.
   >>> dir()
   ['__builtins__', '__doc__', '__name__']
   >>> type(__builtins__)
   <type 'module'>
   >>> __builtins__
   <module '__builtin__' (built-in)>

So as you can see, __builtins__ is an alias for the __builtin__
module.

   >>> spam
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   NameError: name 'spam' is not defined
   >>> __builtins__.spam = 5
   >>> spam
   5

We can change anything in the __builtins__ namespace, and we can
reference it directly (i.e. we don't need to qualify the reference to
'spam' by putting '__builtins__' first.

Now let's define another module, b2:

   print type(__builtins__)
   __builtins__.eggs = 6

Now b2 can join in the namespace fun!

   >>> import b2
   <type 'dict'>
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
     File "E:\PYTHON\lib\b2.py", line 2, in ?
       __builtins__.eggs = 6
   AttributeError: 'dict' object has no attribute 'eggs'


Huh? Why is __builtins__ a dictionary? It's a module when we access it
from the interpreter... let's investigate further...

   >>> dir(b2)
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   NameError: name 'b2' is not defined

D'oh! Of course. Let's comment out both lines in b2, so it doesn't do
anything.

   >>> import b2
   >>> dir(b2)
   ['__builtins__', '__doc__', '__file__', '__name__']
   >>> type(b2.__builtins__)
   <type 'dict'>
   >>> b2.__builtins__['spam']
   5

Hmm... so __builtins__ in b2 is the same thing as we defined in the
interpreter (as it has a value for 'spam'), but it's a dictionary
instead of a module.

This seems such a strange thing to me, can anyone explain why the
value of __builtins__ differs?

Allan.



More information about the Python-list mailing list