What is the right way in Python to import a module from a directory one level up? The directory is a Python package with all these modules and I have a sub directory with co
In your main file recipe.py add pkg1 path to the PYTHONPATH
sys.path.append('/path/to/pkg1')
Or use a relative path
sys.path.append('../..')
This should allow importing pkg1 from any where in your program.
There is always the option of using relative imports as suggested here, I find using absolute imports more readable and less likely to lead to bugs. Also, in large projects using relative imports will have you constantly calculating path hierarchies while when using absolute imports, it's simple to know you always refer to one root directory.
About relative imports from PEP328 in Python 2.5:
Reading code which relies on relative imports is also less clear, because a reader may be confused about which module is intended to be used. Python users soon learned not to duplicate the names of standard library modules in the names of their packages’ submodules, but you can’t protect against having your submodule’s name being used for a new module added in a future version of Python.
Guido is suggesting using leading dots in relative imports to avoid ambiguous imports as described above, from PEP328 again:
Guido has Pronounced that relative imports will use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots give a relative import to the parent(s) of the current package, one level per dot after the first.