2

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
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Maurice Meyer Sep 12 '21 at 18:12
  • 1
    Thanks for this link. The answer from almost 9 years ago does not address what I am asking. After a painful read it concludes "the package directory .. must be accessible from the Python module search path (`sys.path`). If it is not, you will not be able to use anything in the package reliably at all." I refuse to believe almost a decade later this is still the case. – Cloud Living Sep 13 '21 at 04:49

1 Answers1

0

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
robm
  • 1,303
  • 1
  • 16
  • 24