Type of __builtins__ changes from module import to execution?

A

Adam Hupp

I've noticed some unexpected behavior with __builtins__ during module
import. It seems that during module import __builtins__ is a dict
but at all other times it is a module.

For example, if the file testmod.py has these contents:

print type(__builtins__)
print "has str attr", hasattr(__builtins__, 'str')

The output differs depending on how it is run:

$ python ~/testmod.py
<type 'module'>
has str True

vs.

$ python -c 'import testmod'
<type 'dict'>
has str False

Anyone know if there a reason for this behavior? Is it a bug? I've
seen this in 2.4 and 3.0.

-Adam
 
M

Marc Christiansen

Adam Hupp said:
I've noticed some unexpected behavior with __builtins__ during module
import. It seems that during module import __builtins__ is a dict
but at all other times it is a module.

For example, if the file testmod.py has these contents:

print type(__builtins__)
print "has str attr", hasattr(__builtins__, 'str')

The output differs depending on how it is run:

$ python ~/testmod.py
<type 'module'>
has str True

vs.

$ python -c 'import testmod'
<type 'dict'>
has str False

Anyone know if there a reason for this behavior? Is it a bug? I've
seen this in 2.4 and 3.0.

-Adam

No, it's not a bug. __builtins__ is an implementation detail. You want
__builtin__. See <http://docs.python.org/lib/module-builtin.html>

Ciao
Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top