[Poetry](https://python-poetry.org/) is a dependency management and packaging tool for Python projects. It simplifies project setup, dependency resolution, and packaging, making it easier to manage and distribute [[Python]] applications.
## Install
[Install Poetry.](https://python-poetry.org/docs/#installation)
Install the `poetry-plugin-export` to export dependencies into a standard *requirements.txt* file.
```sh
poetry self update
poetry self add poetry-plugin-export
poetry config warnings.export false
```
## Configure
On MacOS, Poetry's `config.toml` and `auth.toml` are located at `~/Library/Application Support/pypoetry`
## Run
### Install commands
Install project dependencies, including **dev** dependencies.
```sh
poetry install
```
To install any other dependency group, specify it.
```sh
poetry install --with other-group
```
Install **all** dependency groups.
```sh
poetry install --all-extras
```
### Other commands
Poetry supports source distribution and wheels.
```sh
poetry build
```
Publish to public or private repositories.
```sh
poetry publish
```
Show the dependency tree.
```sh
poetry show --tree
```
Compare and contrast your dependencies with the latest packages.
```sh
poetry show --latest
```
Preview an upgrade.
```sh
poetry self update --preview
```
Upgrade Poetry.
```sh
poetry self update
```
## Tips
### pyenv
Poetry can become "confused" when switching between different [[_published/Python/pyenv|pyenv]] versions. You may have to [reinstall it](https://stackoverflow.com/a/70064450/154065) with the activated version of [[Python]].
```sh
curl -sSL https://install.python-poetry.org/ | python3.11 -
```
### requirements.txt
Install poetry-plugin-export as a [plugin](https://python-poetry.org/docs/plugins/#using-plugins).
```sh
poetry self add poetry-plugin-export
```
Remove its warning.
```sh
poetry config warnings.export false
```
You can then generate a traditional requirements file from a Poetry TOML file. Here is a [[Makefile]] to do so.
```Makefile
REQUIREMENTS = requirements.txt
# Export the requirements with no environment markers.
$(REQUIREMENTS):
@poetry export --without-hashes -f $(REQUIREMENTS) --output $(REQUIREMENTS)
@sed -i '' 's/[[:space:]]*;.*//' $(REQUIREMENTS)
```
### Timeouts
If Poetry times out when fetching packages, try extending its timeout.
```sh
export POETRY_HTTP_TIMEOUT=240
```
## Resources
- [Package Python Projects the Proper Way with Poetry](https://hackersandslackers.com/python-poetry-package-manager/)
- [Create and Publish a Python Package with Poetry](https://johnfraney.ca/posts/2019/05/28/create-publish-python-package-poetry/)
- [Run a Poetry script](https://stackoverflow.com/a/59316578/154065)
- [Configuration | Poetry](https://python-poetry.org/docs/configuration/)
### Poetry & [[VS Code]]
- [How to debug Poetry with VS Code](https://fredrikaverpil.github.io/blog/2021/04/17/debugging-poetry-with-visual-studio-code)
- [Debugging issue | GitHub](https://github.com/python-poetry/poetry/issues/5354)