PYTHONPATH vs. sys.path

gaefan picture gaefan · Dec 12, 2009 · Viewed 101k times · Source

Another developer and I disagree about whether PYTHONPATH or sys.path should be used to allow Python to find a Python package in a user (e.g., development) directory.

We have a Python project with a typical directory structure:

Project
    setup.py
    package
        __init__.py
        lib.py
        script.py

In script.py, we need to do import package.lib. When the package is installed in site-packages, script.py can find package.lib.

When working from a user directory, however, something else needs to be done. My solution is to set my PYTHONPATH to include "~/Project". Another developer wants to put this line of code in the beginning of script.py:

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

So that Python can find the local copy of package.lib.

I think this is a bad idea, as this line is only useful for developers or people running from a local copy, but I can't give a good reason why it is a bad idea.

Should we use PYTOHNPATH, sys.path, or is either fine?

Answer

Ned Batchelder picture Ned Batchelder · Dec 12, 2009

If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run setup.py develop to semi-install the working tree in your current Python installation.