Search code examples
pythonpython-poetry

How to specify python paths in pyproject.toml for poetry?


I want to build a poetry python environment by setting the pyproject.toml file so when I activate it and running in python interpreter import sys; print(sys.path) will show the paths added in pyproject.toml

How to proceed ?


Solution

  • You can use tool.poetry.packages and their from attribute so that those paths are added to the *.pth file managed by poetry when installing.

    This example pyproject.toml

    [tool.poetry]
    name = "asdf"
    version = "0.1.0"
    description = ""
    authors = ["Your Name <you@example.com>"]
    readme = "README.md"
    
    packages = [
        { include = "foo", from = "lib" },
        { include = "bar", from = "src"},
    ]
    
    
    [tool.poetry.dependencies]
    python = "^3.11"
    
    
    [build-system]
    requires = ["poetry-core"]
    build-backend = "poetry.core.masonry.api"
    

    with the following folder tree

    |-- pyproject.toml
    |-- README.md
    |-- src
    |   \-- bar
    |       \-- __init__.py
    \-- lib
        \-- foo
            \-- __init__.py
    

    when installed with poetry install will create a myproject.pth file in the virtual environment such that

    python -c 'import os,sys; print(os.linesep.join(sys.path))'
    

    will contain

    /path/to/my/projects/asdf/src
    /path/to/my/projects/asdf/lib
    

    Make sure to read the documentation to understand all caveats, e.g.

    Using packages disables the package auto-detection feature meaning you have to explicitly specify the “default” package.

    https://python-poetry.org/docs/pyproject/#packages