Overview

Poetry is a dependency management and packaging tool for Python. I have been using it for a while and I really love it since it help simplify the process of managing dependencies and virtual environments.

Installation

If you have pip installed in your machine. Run the following command to install Poetry. Otherwise, follow this guide.

pip install poetry

Check if Poetry is installed successfully:

$ poetry --version
Poetry (version 1.8.2)

Create New Project

To create a new project:

poetry new my-project

To initialize Poetry for an existing project:

poetry init

Naming Convention

The official doc recommends using kebab case, for example: poetry-demo. Peotry will create a package folder using the snake case inside the project, for example: poetry_demo.

Here’s the folder with skeleton structure from the Poetry’s basic usage page:

poetry-demo
├── pyproject.toml
├── README.md
├── poetry_demo
│   └── __init__.py
└── tests
    └── __init__.py

Change Package Name

If you don’t like the package name for some reason, you can change it to something else. After the update, remember to update the pyproject.toml.

For example:

# Rename poetry_demo to app
mv poetry_demo app

Then update:

# pyproject.toml
-- name = "poetry_demo"
++ name = "app"

Virtual Environment

Tell Poetry to create a virtual environment inside the project by running:

poetry config virtualenvs.in-project true

A virtual environment will be created inside the project:

poetry-demo
├── .venv
│   └── Lib
│       └── site-packages
│           └── uvicorn

To configure VSCode to use the virtual environment:

  • Ctrl + Shift + P
  • Python: Select Interpreter
  • Use the python.exe in the .venv folder

Manage Dependencies

Add prod dependencies:

poetry add prod-package

Add dev dependencies:

poetry add -D dev-package

Install Dependencies

Note that adding dependencies doesn’t mean installing dependencies. You will still install them by running:

poetry install

Start Script

In the pyproject.toml, add a section called tool.poetry.scripts. Assuming you have a main.py inside the poetry_demo folder:

[tool.poetry.scripts]
start = "poetry_demo.main:app --reload"

Then run the application with:

poetry run start