Home > OS >  Module not found error with Python in Docker
Module not found error with Python in Docker

Time:12-15

My directory structure

    .
    |--app
    |   |--__init__.py
    |   |--main.py
    |  
    |
    |--Dockerfile
    |--requirements.txt

I can build this and run it fine. But when I add another *.py file to my project, like this

    .
    |--app
    |   |--__init__.py
    |   |--main.py
    |   |--handler.py
    |
    |--Dockerfile
    |--requirements.txt

and I try to import a function from handler.py in main.py, like this

# main.py
from handler import someFunc

then main.py gives me a NoModuelFound error for handler.py . Can someone explain how to fix this (and maybe also explain why this error is happening)?

CodePudding user response:

Print out your sys.path as one of the first things you do in your application, there's a good chance it's not set in such a way to get easy access to the stuff under app.

The Google style guide (the one we follow at work (and I at home), and also the ones that have gotten us out of the bad habit of fiddling around with PYTHONPATH) have two rules applicable here.

  • Use absolute imports; and
  • Don't import anything less than a module.

That would involve importing (and using) as follows:

from app import handler
handler.someFunc()

If you're not amenable to using those guidelines, you have to figure out why handler is not available. This could be because it's not imported in the __init__.py file (making it a "re-export" on the package level), or possibly you need to reach down to handler the same way you have to main.

Without more code/info, it's hard to tell how to fix it but my advice is to go the Google way :-)

  • Related