Absolute import results in ModuleNotFoundError

Viewed 3472

Python 3.6

I've written some components and I'm trying to import one of them in the other.

Below is what my project structure looks like:

.
└── components
    ├── __init__.py
    ├── extract
    │   └── python3
    |       ├── __init__.py
    │       └── extract.py
    └── transform
        └── python3
            ├── __init__.py
            └── preprocess.py

extract.py

from components.transform.python3.preprocess import my_function

if __name__ == '__main__':
    my_function()

preprocess.py

def my_function():
    print("Found me")

When I run python components/extract/python3/extract.py

I see the following error:

ModuleNotFoundError: No module named 'components'

I've added an empty __init__.py file to the directories that contain modules as well as the top level package directory.

1 Answers

Ok, imports require the top level package to be available in Python PATH (sys.path).

So to make it work, you should:

  • cd to the directory containing components
  • add . to the Python PATH:

    export PYTHONPATH='.'
    
  • launch your script:

    python components/extract/python3/extract.py
    

On my system, it successfully displays:

Found me
Related