2 min read

Python Poetry for Dependency Management

Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. It aims to replace setup.py, requirements.txt, setup.cfg, MANIFEST.in, and Pipfile with a simple pyproject.toml based project format.

Installation

Linux, macOS, Windows (WSL)

curl -sSL https://install.python-poetry.org | python3 -

Windows (Powershell)

(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -

Basic Usage

Initializing a Project

To create a new project:

poetry new my-project

To initialize poetry in an existing directory:

cd my-existing-project
poetry init

This will guide you through creating a pyproject.toml file.

Adding Dependencies

To add a package to your project:

poetry add requests

To add a development dependency (e.g., for testing):

poetry add pytest --group dev

Installing Dependencies

To install the dependencies defined in pyproject.toml:

poetry install

This command reads the poetry.lock file if it exists, ensuring reproducible builds. If not, it resolves dependencies and creates the lock file.

Virtual Environments

Poetry automatically creates and manages a virtual environment for your project.

Activating the Environment

To spawn a shell within the virtual environment:

poetry shell

To run a single command within the environment without activating the shell:

poetry run python script.py

Configuration

You can configure Poetry to create virtual environments inside the project directory (similar to venv).

poetry config virtualenvs.in-project true

The pyproject.toml File

This is the main configuration file.

[tool.poetry]
name = "my-project"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]

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

[tool.poetry.group.dev.dependencies]
pytest = "^7.1.2"

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

programming/python/python