Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute import results in ModuleNotFoundError

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.

like image 335
Jonathan Porter Avatar asked Jan 08 '19 21:01

Jonathan Porter


People also ask

Should I use relative or absolute imports Python?

With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.


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
like image 125
Serge Ballesta Avatar answered Nov 06 '22 06:11

Serge Ballesta