Import python from sibling folder without -m or syspath hacks

Viewed 41

So I've spent the last three days trying to figure out a workable solution to this problem with imports.

I have a subfolder in my project where I have scripts for database control, which has sibling folders that would like to call it. I have tried many online solutions but couldn't find anything that properly works. It seems some changes in Python 3.3/4 nullify a lot of solutions, or something.

So I made a very simple test case.

IMPORTS/
├─ folder1/
│  ├─ script1.py
│  ├─ __init__.py
├─ folder2/
│  ├─ script2.py
│  ├─ __init__.py
├─ __init__.py

How do I, from script1.py, call a function inside script2.py?

1 Answers

I generally prefer to install my module as a dependency so I can import from the project root. This seems to be the correct approach, though I've rarely seen it talked about online.

E.g. from IMPORTS you would run pip install -e . (install the package in this folder in editable mode). This will require that you have a setup.py:

from setuptools import setup, find_packages

setup(
    name='IMPORTS',
    version='x.x.x',
    description='What the package does.',
    author='Your Name',
    author_email='x@x.com',
    install_requires=[],
    packages=find_packages()
)

Here is an example from one of my personal packages.

Then you can import from the root folder (where setup.py is). Following your example:

from folder1 import script1

Or vice versa.

In summary:

  1. Write a setup.py.
  2. Install your package in editable mode with pip install -e .
  3. Write import statements from the package root.
Related