Search code examples
pythonpython-poetry

How does Poetry associate a project to its virtual environment?


How does Poetry associate a project to its virtual environment in ~/.cache/pypoetry/virtualenvs? I can't find any link inside the project, e.g. grep -ie NKJBdMnE . returns nothing.

poetry env info:

Virtualenv
Python:         3.10.11
Implementation: CPython
Path:           /home/lddpro/.cache/pypoetry/virtualenvs/lxxo-NKJBdMnE-py3.10
Executable:     /home/lddpro/.cache/pypoetry/virtualenvs/lxxo-NKJBdMnE-py3.10/bin/python
Valid:          True

System
Platform:   linux
OS:         posix
Python:     3.10.11
Path:       /var/lang
Executable: /var/lang/bin/python3.10

poetry config --list:

[lddpro@0a0aecf400ca lddpro-bff]$ poetry config --list
cache-dir = "/home/lddpro/.cache/pypoetry"
experimental.new-installer = true
experimental.system-git-client = false
installer.max-workers = null
installer.no-binary = null
installer.parallel = true
virtualenvs.create = true
virtualenvs.in-project = null
virtualenvs.options.always-copy = false
virtualenvs.options.no-pip = false
virtualenvs.options.no-setuptools = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}/virtualenvs"  # /home/lddpro/.cache/pypoetry/virtualenvs
virtualenvs.prefer-active-python = false
virtualenvs.prompt = "{project_name}-py{python_version}"

https://python-poetry.org/docs/configuration/


Solution

  • The path to the virtual environment is generated on the fly. It is not stored anywhere. The 8 letters NKJBdMnE are a part of the SHA256 of the working directory of you project. If you move your project into a different directory, poetry will use a different virtual environment as the SHA256 will be different.

    You can see the exact algorithm used in the poetry source code: env.py#L1196-L1204