Search code examples
pythonpython-importpython-packagingpython-poetry

Poetry cannot import from subfolders in scripts runned by "poetry run"


Project structure is like this:

.
├── README.md
├── pyproject.toml
...
my_project_name/
    ├── moduleA.py
    ├── moduleB.py
    └── FolderC
        └── moduleC.py

moduleA.py:

from .moduleB import moduleB_func
from .FolderC.moduleC import moduleC_func
...

script in pyproject.toml:

funcA_run = my_project_name.moduleA:funcA

(funcA function is just example - exception appears on start of compiling at the second line on import)

If i type poetry run funcA_run in project directory (where my_project_name folder, readme.rst, pyproject.toml and other poetry files), moduleB imports successfully, but moduleC from subfolder is not:

ImportError: cannot import name 'moduleC_func' from 'FolderC' (unknown location)

Removing . from import doesn't help.

With import FolderC.moduleC.moduleC_func i getting

ModuleNotFoundError: No module named 'FolderC.moduleC_func'

If moduleC.py import would be in moduleB.py, same will happen.

So, because of this i can't run any scripts, that contains local relative imports from my project.

Poetry version is 1.1.14

EDIT: Problem as it shown in this question is unreproducable. More details in my answer.


Solution

  • Problem is resolved in some sense. Somewhy, poetry run requires another format of imports.

    With structure like this:

    ├── README.md
    ├── pyproject.toml
    ...
    my_project_name/
        ├── moduleA.py
        └── FolderC
            └── moduleC.py
            └── moduleC_2.py
    

    If moduleC.py imports something from moduleC_2.py, and i import moduleC.py in moduleA.py, imports should look different if two cases:

    If i run moduleA.py as script with poetry run:

    # moduleA.py:
    from .FolderC import moduleC.py  # with .
    
    # moduleC.py
    from .moduleC import some_func  # relatively folderC and with .
    

    If i run moduleA.py manually with python moduleA.py:

    # moduleA.py:
    from FolderC import moduleC.py  # without .
    
    # moduleC.py
    from folderC.moduleC import some_func  # relatively my_project/ and without .