[Tutor] problem importing class

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Oct 28 06:29:52 CEST 2006


>> It looks like people have identified the problem, that your site.py 
>> module isn't being found because it conflicts with something from 
>> Python's Standard Library.
>>
>> This isn't the first time this kind of problem has hit people.  This
>> problem is well known and is the subject of a Python Enhancement Proposal
>> (PEP 328).  If you're using Python 2.5, you can use a new feature called
>> 'absolute_import' to avoid the import problem.  See:
>>
>>      http://docs.python.org/whatsnew/pep-328.html
>>
>> for more details.
>
> Hmm, I don't see how that would help since AFAICT shawn's site.py is not 
> in a package. Or maybe I don't understand what you are suggesting?

Hi Kent,

I don't think I replied back to you on this one!  Python loads up 
'site.py' on startup if called without the '-S' option:

     http://docs.python.org/lib/module-site.html

So imagine if we're a program, and we run Python on it.  For some reason 
--- at least on startup --- Python places precendence on the modules 
located in Python's library directory.  So we pick up the Standard 
Library's site.py, which is then cached in sys.modules like any other 
module import.

Later on, if we try to 'import site', Python reuses the already-loaded 
site.py (because it's already cached in sys.modules) , regardless if 
there's a 'site.py' module in the current working directory.  The reason 
PEP 328 can be a solution here is because, if the absolute_import feature 
were on, we'd be able to do:

     from . import site

which would pick up the correct relative path.


Concretely, here's what probably happened with the original poster:

##############################################################################
mumak:~ dyoo$ echo "print 'hi'" > site.py
mumak:~ dyoo$ python
Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> print site.__file__
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site.pyc
###############################################################################

Note that the 'site.py' in the current directory was not used.  I have no 
idea why.  I suspect that this has some relation to the way that site.py 
is handled by a special case in the Python interpreter, but I have really 
no clue.


Python's module import lookup was handled in an implicit way which goes 
against its traditional "explicit instead of implicit" philosophy. 
That's why PEP 328 is so critically important: the name-collision problem 
gets much worse as either Standard Library or our own programs grow.  I'm 
amazed that we've been able to tolerate this situation for so long. 
*grin*


More information about the Tutor mailing list