How to handle sys.path in bigger projects?

Ype Kingma ykingma at accessforall.nl
Sat Oct 13 16:45:52 EDT 2001


Georg,

you wrote:
> 
> On 12 Oct 2001 11:52:30 +0200, Martin von Loewis
> <loewis at informatik.hu-berlin.de> wrote:
> 
> >Georg Lohrer <GeorgLohrer at gmx.de> writes:
> >
> >> What are your ways of handling?
> >
> >If you are relying on a lot of third-party packages, I'd require that
> >those packages get properly installed, ie. into site-packages or
> >site-python. Then you only need to find your own code.
> 
> I'm only bothered by my own code :-)
> 
> >
> >If that grows in size, organizing it into multiple packages seems to
> >be appropriate. I then see no problem in keeping all these packages in
> >a single directory.
> 
> Ok. Let's have a look on it:
> 
> 1) actual dir contains directory: "myproject" with its __init__.py
> importing myproject.foo1 and myproject.foo2

What is the point of these imports in an __init__.py file?

> 2) two sub-packages (directories) called "foo1" and "foo2" with each
> containing a __init__.py are within "myproject"
> 3) foo1 contains foo1foo.py; foo2 contains foo2foo.py
> 4) foo2foo.py has a intra-package reference to foo1foo.py:
> import myproject.foo1.foo1foo
> 
> Running from parent-dir of "myproject"
> 
> ~user> python
> >>> from myproject.foo1 import foo1foo
> >>>
> 
> runs successfully. But if I want to test the foo1foo.py module itself,
> following the path to myproject/foo1:
> 
> ~user/myproject/foo1> python
> >>> import foo1foo
> *** ImportError: No module named myproject.foo2

I suppose foo1foo.py contains sth like

from myproject.foo2 import whatever

causing the error message.
Your problem is that the current directory is always the first
thing on sys.path. Running from ~user everything is fine, because
that happens to be your "project home". Running from ~user/myproject/foo1
the directory ~user is not on sys.path causing your problem.

> 
> So, the only way that seems to work is to start debugging from most
> upper directory, if there are intra-package references? Is that
> correct? Or how do you handle this?

You might start by making sure that ~user/myproject is always on 
sys.path when you invoke python. This will allow you to get rid of
the myproject package altogether.

One way to do this is by using a small script that checks the
current directory and when it is not ~user/myproject it adds it to
the PYTHONPATH environment variable before invoking python.
You might also set it in your shell's .*rc file.

The above two suggestions are independent: you might also keep
myproject and make sure ~user is on PYTHONPATH when invoking python.
 
Good luck,
Ype

-- 
email at xs4all.nl



More information about the Python-list mailing list