Search code examples
python-3.xpackageimporterrorpython-poetry

ModuleNotFoundError when importing my package, but not when running it alone


I'm trying to create a python package, and I have have trouble with the imports. My code works as expected when running it, but when I install the package using poetry and import it in another script, I have a ModuleNotFoundError.

My file structure is the following :

git_repo
|  myapp
|  |--__init__.py
|  |--mainscript.py
|  |--library
|  |  |--__init__.py
|  |  |--module.py

My file mainscript.py imports the module.py because there are some utility functions : from library import module

When I execute the mainscript, no problem. However, when installing myapp using poetry install and trying to import it in a python shell :

> python

>>> import myapp.mainscript

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\path\to\mainscript.py", line 5, in <module>
    from library import module
ModuleNotFoundError: No module named 'library'

Is there a mechanic I don't understand with the imports ? Do I have to write something in the __init__.py files ?

Thanks in advance for your help


Solution

  • Okay so I found a solution to my own problem.

    As J_H suggested, I tried relative imports. This worked when installing my package and using it. But I encountered ImportError: attempted relative import with no known parent package when running my mainscript.

    The solution was to use absolute imports. Now this works both when installing the package and running the mainscript.

    # mainscript.py
    from myapp.library import module
    

    I also added some imports in the __init__.py files in order to ease the use of my package when installed :

    # myapp/__init__.py
    from . import library
    from .mainscript import mainClass
    

    This allows me to do a = myapp.mainClass() instead of a = myapp.mainscript.mainClass()