tyrex
tyrex

Reputation: 8919

How does the Python tool Poetry know the path of a project's virtual environment?

My question: How does the Python tool Poetry know the path of the virtual environment of a project?

Explanation: When I run poetry init inside a directory, a new project is created. Then I run poetry install and a new virtual environment is created. HOWEVER, neither the path nor the hash of that virtual environment are stored in pyproject.toml or poetry.lock as I expected. How does Poetry then know the location of the virtual environment when I run poetry env info -p?

Besides wanting to know what is going on, I need to know this for 2 reasons:

Possible solution: Looking into the source code of Poetry, it seemed to me that a file envs.toml may include a mapping from filesystem directories to virtual environment hashes, but on my Mac OS 11.1 I can't find such a file.

Upvotes: 19

Views: 8390

Answers (2)

tyrex
tyrex

Reputation: 8919

I dived deeper into the source code and I may have understood it now:

  • The relevant code is at poetry/utils/env/env_manager.py inside the class method EnvManager.generate_env_name(...)(src)
  • The code deduces the location of the environment by using the project name from pyproject.toml and adding the hash of the parent directory of pyproject.toml

As a consequence:

  • There is no simple way to delete environments which are not used anymore
  • Also, if I want to move the directory of a poetry project, I would need to rename the virtual environment's folder and replace the hash correctly. This should work, but it would be preferable to just run poetry install again and create a new virtual environment

Upvotes: 18

echo
echo

Reputation: 480

There's a poetry config variable that makes poetry install the virtual environment inside the project. Thus, if you delete the project directory, the venv will also be deleted. It also allows you to inspect what's in the venv, and delete/recreate the venv when needed.

From the cmd line: poetry config virtualenvs.in-project true

Verify it's set: poetry config --list (virtualenvs.in-project should be true)

Upvotes: 2

Related Questions