Package question.

I

Ian Sparks

I'm sure its been thrashed through a hundred times but googling for an answer left me more confused than before and yes, I did read the Tutorial (maybe not well enough, but I read it).

On Windows, I want to set up a package structure like :

Fred
Bob
test.py

So I can say :

from Fred.Bob import *

To do this I need to put the package on the python path. So I drop this into my python root in a file called Fred.pth :

C:\Fred\

Now I need to make sure that Fred and Bob both look like packages with empty __init__.py files like so :

C:\Fred
__init__.py
C:\Fred\Bob
__init__.py
test.py

so :

C:\python.exe -c from Fred.Bob import *

OK!

But if I do :

C:\>cd Fred
C:\Fred>python.exe -c "from Fred.Bob import *"
Traceback (most recent call last):
File "<string>", line 1, in ?
ImportError: No module named Fred.Bob

Now lets say I change my Fred.pth contents to C:\MyTest and put my whole directory structure under c:\MyTest :

C:\MyTest\Fred
__init__.py
C:\MyTest\Fred\Bob
__init__.py
test.py


C:\>cd MyTest\Fred
C:\MyTest\Fred>python.exe -c "from Fred.Bob import *"

Works fine.

Is this quirk expected? If yes, I would like to expand my python knowledge with the why.

Thanks for your attention on this long post.
 
S

Scott David Daniels

Ian said:
... On Windows, I want to set up a package structure like :
Fred\
Bob\
test.py
So I can say :
from Fred.Bob import *
To do this I need to put the package on the python path.
> So I drop this into my python root in a file called Fred.pth :
C:\Fred\
Now to make sure that Fred and Bob both look like packages with
> empty __init__.py files like so :
C:\Fred\
__init__.py
C:\Fred\Bob\
__init__.py
test.py
so :
C:\python.exe -c from Fred.Bob import *
OK!
But this is a lucky accident. If you do:
import sys
for number, name in enumerate(sys.path):
print number, repr(path)
You'll see (I suspect) that '' is on your path, and the Fred.pth
value is irrelevant (it adds an entry for 'C:\\Fred\\', which allows
you to import from Bob, not Fred. You Fred.pth file should list the
directory _containing_ Fred (in this case, 'C:\\', not 'C:\\Fred\\').

Note, you'll still be surprised soon, because I suspect you think
that after:
from Fred.Bob import *
you can freely use:
test.somefunction()

-Scott David Daniels
(e-mail address removed)
 

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
474,266
Messages
2,571,342
Members
48,018
Latest member
DelilahDen

Latest Threads

Top