Well, that was interesting enough for me to experiment a bit and I read through http://docs.python.org/reference/executionmodel.html
Then did some tinkering with your code here and there, this is what i could find:
code:
import pprint
def two():
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
print globals()['pprint']
def main():
if 'pprint' in globals():
print 'pprint is in globals()'
global pprint
print globals()['pprint']
pprint.pprint('Spam')
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
def three():
print globals()['pprint']
pprint.pprint('Spam')
if __name__ == '__main__':
two()
print('\n')
three()
print('\n')
main()
output:
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Eggs'
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
pprint is in globals()
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
<function pprint at 0xb7d596f4>
'Eggs'
In the method two() from pprint import pprint but does not override the name pprint in globals, since the global keyword is not used in the scope of two().
In method three() since there is no declaration of pprint name in local scope it defaults to the global name pprint which is a module
Whereas in main(), at first the keyword global is used so all references to pprint in the scope of method main() will refer to the global name pprint. Which as we can see is a module at first and is overriden in the global namespace with a method as we do the from pprint import pprint
Though this may not be answering the question as such, but nevertheless its some interesting fact I think.
=====================
Edit Another interesting thing.
If you have a module say:
mod1
from datetime import datetime
def foo():
print "bar"
and another method say:
mod2
import datetime
from mod1 import *
if __name__ == '__main__':
print datetime.datetime.now()
which at first sight is seemingly correct since you have imported the module datetime in mod2.
now if you try to run mod2 as a script it will throw an error:
Traceback (most recent call last):
File "mod2.py", line 5, in <module>
print datetime.datetime.now()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
because the second import from mod2 import * has overriden the name datetime in the namespace, hence the first import datetime is not valid anymore.
Moral: Thus the order of imports, the nature of imports (from x import *) and the awareness of imports within imported modules - matters.