Package organization: where to put 'common' modules?

Kent Johnson kent at kentsjohnson.com
Sun Mar 5 18:57:07 EST 2006


fortepianissimo wrote:

 > Hm this doesn't work. Say I have the following directory structure:
 > A
 > |--- util
 > |    |--- foo.py
 > |
 > |--- B
 >      |--- bar.py
 >
 > And bar.py has this line
 >
 > from util import foo
 >
 > I then run
 >
 > python B/bar.py
 >
 > in directory A. Still got error
 >
 > ImportError: No module named util


Do you have a file util/__init__.py? This is required to make python 
recognize util as a package.

This works for me:
C:\WUTemp\A>dir /b/s
C:\WUTemp\A\B
C:\WUTemp\A\util
C:\WUTemp\A\B\bar.py
C:\WUTemp\A\B\__init__.py
C:\WUTemp\A\util\foo.py
C:\WUTemp\A\util\foo.pyc
C:\WUTemp\A\util\__init__.py
C:\WUTemp\A\util\__init__.pyc

C:\WUTemp\A>type util\foo.py
def baz():
     print 'foo.baz() here'

C:\WUTemp\A>type B\bar.py
import sys
print sys.path

from util import foo
foo.baz()

C:\WUTemp\A>python B\bar.py
['C:\\WUTemp\\A\\B', 'C:\\Python24\\python24.zip', 'C:\\WUTemp\\A', 
<snip lots more dirs>]
foo.baz() here

Kent



More information about the Python-list mailing list