Search code examples
python-poetry

How can I make my project available in the poetry environment?


I want to be able to run/import my packages during development, using poetry as my dependency and environment management tool. I simply cannot figure out how to do this in poetry (without manipulating sys.path in every interpreter)

The poetry documentation seems to indicate that this should be done by default:

The current project is installed in editable mode by default.

But I have tried this with multiple projects, and the current project is never able to be imported from the interpreter in the virtual env. It always fails with a ModuleNotFoundError. I also cannot see how or where this installation is supposed to happen.

The docs also describe adding path dependencies in editable mode:

[tool.poetry.dependencies]
my-package = {path = "../my/path", develop = true}

but this always fails with "can't open file" or "Directory does not seem to be a python package". The directory has __init__.py, and I am using the default poetry setup with a src directory.


Solution

  • There are two things needed, that the package under development is available in the venv.

    First, poetry must be able to find the package folder. poetry is able to do this by default, if the folder containing the package data is located in the same folder as the pyproject.toml or is a subfolder of a folder called src. The name of the folder containing the package data must be the same as defined under name in the [tool.poetry] section of the pyproject.toml. In case name contains . or - these characters must be replaced by _ for the package folder.

    If you are using a different schema, you have to tell poetry via packages in your pyproject.toml where it can find the packages, e.g.:

    packages = [
        { include = "my_package", from = "lib" },
    ]
    

    See the docs for more example.

    Second, run poetry install. This will install all dependencies and install the projects package in editable mode as well in a virtual environment.

    Don't forget to activate the venv if you start working. This can be done via poetry shell or run the script via poetry run python my_script.py.