bluesummers
bluesummers

Reputation: 12607

Modifying Poetry's virtual environment PYTHONPATH

I'm using Poetry to manage dependencies - NOT as a packaging tool. Given the following layout

.
├── poetry.lock
├── pyproject.toml
├── src
│   ├── __init__.py
│   └── my_module.py
└── scripts
    └── my_script.py

Inside my_script.py I'm using from src.my_module import MyClass but when I call poetry run python scripts/my_script.py I get:

ModuleNotFoundError: No module named 'src'

I want to add the root directory to the PYTHONPATH of this specific environment, but I want to avoid manually exporting it everytime.

Bottom line I'm looking for Poetry's equivalent for vitualenvwrappers add2virtualenv

Is this possible under Poetry?

Upvotes: 12

Views: 16917

Answers (2)

bluesummers
bluesummers

Reputation: 12607

Eventually, I wrote a small .sh script, that permanently adds the project directory to the environment created by poetry.

This is the script, add2pythonpath.sh

#!/usr/bin/env sh
# Add current folder to PYTHONPATH
CURRENT_FOLDER=$(pwd)
SITE_PACKAGES_FOLDER="$(ls -d $(poetry env info -p)/lib/python*/site-packages/)project_dir.pth"
echo "$CURRENT_FOLDER" > "$SITE_PACKAGES_FOLDER"

If you execute this inside your project directory, the current folder (project directory) will be permanently be added to the PYTHONPATH for your Poetry-created virtual environment.

It is utilizing .pth files to do so. You can read more about how those files are relevant for that in this link: https://docs.python.org/3/library/site.html#:~:text=A%20path%20configuration,tab%29%20are%20executed.

Upvotes: 4

finswimmer
finswimmer

Reputation: 15152

You can put your my_module.py directly into the src folder, but this is not recommended. Create a package folder first which then contains all your modules.

project
├── poetry.lock
├── pyproject.toml
├── scripts
│   └── my_script.py
└── src
    └── project
        ├── __init__.py
        └── my_module.py

With a pyproject.toml like this:

[tool.poetry]
name = "project"
version = "0.1.0"
description = ""
authors = ["finswimmer <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.9"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

Don't forget to run poetry install once. This will install the project in editable mode.

Upvotes: 4

Related Questions