importing a parent folder python script for subfolder script (no sys.path workaround please)

Viewed 160

With this structure:

my-project/
|--- useful_functions.py/
|--- subfolder/
    |--- script.py

How to allow script.py to access the useful_functions.py (one level up), preferably NOT using sys.path for this? My cousin says I should simple put my-project folder into anaconda's site-packages and then use import my-project.useful_functions, is that good practice?

1 Answers

The simplest answer seems to be:

(1) Create this structure:

my-project/
| setup.py
| __init__.py
|--- useful_functions/
     |--- __init__.py
     |--- useful.py
|--- subfolder/
     |--- __init__.py
     |--- script.py

The __init__.py files can be empty. The setup.py file apparently needs only:

from distutils.core import setup
setup(name='my-project',
      version='0.1',
      py_modules=['my-project'],
      )

(2) In my-project/ execute pip3 install -e .

Now script.py can use:

from useful_functions.useful import useful_fn

This comes partly from this SO answer and lots of trial-and-error, and IMHO is far more complicated than it needs to be. Happy to see easier and better approaches from others.

Also, if you need to import from a sibling file in useful_functions, like:

|--- useful_functions/
     |--- __init__.py
     |--- useful.py
     |--- useful2.py

in useful2.py it would be:

from .useful_functions.useful import useful_fn
Related