Tuesday, April 22, 2008

Temporary additions to the Python sys.path

You've got some file /foo/bar/bar.py that, for whatever, needs to import Foo from the parent directory in /foo/foo.py. How does /foo/bar/bar.py import from /foo/foo.py?

Option 1. Put /foo in PYTHONPATH.

Option 2. Turn both the /foo and /foo/bar directories into packages. Stick an __init__.py file in /foo and stick another __init__.py file in /foo/bar. You've then got a pair of packages, one containing the other. Relative import from .. foo import Foo syntax will now work in /foo/bar/bar.py provided that you import /foo/bar/bar.py as a package and do not execute /foo/bar/bar.py from the commandline as a script. This last bit got me. Kept getting Attempted relative import in non-package exceptions.

Option 3. Stick /foo in sys.path, use plain old from foo import Foo syntax, and then rip /foo back out of sys.path. At the top of bar you can have, for example

import sys
sys.path.insert(1, '/foo')
from foo import Foo
sys.path.remove('/foo')
...

This works because sys.path is just a list.

No comments: