0

There is a popular Python question called Importing files from different folder.

But the top answer there mentions adding stuff to "some_file.py", and that will obviously only apply to imports inside that file.

What if I want to specify an additional dir to import from, project-wide?

I don't want to modify PYTHONPATH, as I believe a per-project solution is cleaner.

I don't want to use python packages for this, because I feel they'll probably just complicate stuff. E.g. maybe I'll need to manually recompile .py files into .pyc files every time I make a change to the code in the other folder.

Stefan Monov
  • 11,332
  • 10
  • 63
  • 120
  • Dynamically alter python path at run time? – Sam Redway Jan 20 '18 at 09:13
  • No need to *... manually recompile .py files into .pyc files every time I make a change to the code in the other folder.*. Just use a package that is what they are for. – Mike Müller Jan 20 '18 at 09:15
  • @MikeMüller: Ok, I just read [this tutorial](https://www.pythoncentral.io/how-to-create-a-python-package/) and it doesn't say how another project can find a package that I've created. And [this one](https://python-packaging.readthedocs.io/en/latest/) explains how to "make trouble-free packages for community use" which is not what I want. – Stefan Monov Jan 20 '18 at 09:18

1 Answers1

1

What if I want to specify an additional dir to import from, project-wide?

Solution 1: Package installed in develop mode

Create a regular package with setup.py and install it with -e option:

python -m pip install -e /path/to/dir_with_setup_py/

-e, --editable Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url.

Now, as soon as you update your code, the new version will be used at import without reinstalling anything.

Solution 2: Dynamically modify sys.path

You can add as many directories dynamically to the search path for Python packages as you want. Make this the very first lines of code you execute:

import sys

sys.path.append('my/path/to/my/file1')
sys.path.append('my/path/to/my/file2')

or to make the first to be found:

sys.path.insert(0, 'my/path/to/my/file1')
sys.path.insert(0, 'my/path/to/my/file2')

Now the files:

my/path/to/my/file1/myscript1.py
my/path/to/my/file2/myscript2.py

can be imported anywhere in your project:

import myscript1
import myscript2

No need to modify sys.path again as long as this Python process is running.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161