python package imports during development

During development I don’t always want to run the package from it’s main entry point (usually the current working directory when running it). Sometimes I want to quickly test a sub module, potentially in a subdirectory a few levels deep from that subdirectory.

For example:

project
- project (src)
-- subdir level 1
--- subdir level 2

in subdir level 2, a ‘mod_I_want_to_run.py’ python module has:

from project.subdir_level_1 import other_module

When running this from subdir level 2, python will correctly give import errors as project has not been added to PYTHONPATH or to the sys.

My two favourite methods for coping with this are:

1. run the module from the project dir using ‘-m’:

python -m project.subdir_level_1.mod_I_want_to_run

2. add the project directory to virtualenvwrappers path, using add2virtualenv.

add2virtualenv ~/project

From the docs:

The directory names are added to a path file named _virtualenv_path_extensions.pth inside the site-packages directory for the environment.

python package imports during development

Leave a comment