Modern Python Dependency Management with Poetry

Overview

represents a shift in how developers handle the
Python
ecosystem. It moves beyond the fragmented landscape of requirements.txt and setup.py, consolidating dependency management, virtual environment isolation, and package publishing into a single workflow. By utilizing the pyproject.toml standard defined in
PEP 518
, it ensures that your project remains reproducible and clean across different machines.

Modern Python Dependency Management with Poetry
Python Poetry in 8 Minutes

Prerequisites

To follow this guide, you should have a basic understanding of the terminal or command line. Familiarity with

syntax and the concept of third-party libraries is necessary. You should have
Python
installed on your system, ideally version 3.8 or higher.

Key Libraries & Tools

  • Poetry: The primary tool for dependency management and packaging.
  • PyPI: The
    PyPI
    , where Poetry fetches and publishes packages.
  • Virtual Environments: Isolated spaces where your project dependencies live.

Code Walkthrough

Managing dependencies involves a few core terminal commands. To add a new library like

, use the add command:

poetry add pytest

This command updates your pyproject.toml and creates a poetry.lock file. The lock file is crucial; it records the exact versions of every sub-dependency installed, preventing the "it works on my machine" syndrome. To see what is currently installed, run:

poetry show

To enter the isolated environment created by Poetry, use the shell command:

poetry shell

Syntax Notes

Poetry uses specific symbols for versioning in pyproject.toml. The caret (^) symbol is the default. For example, ^2.3.0 allows updates that do not change the left-most non-zero digit (e.g., up to but not including 3.0.0). The tilde (~) symbol is more restrictive, typically allowing only patch-level changes if a minor version is specified.

Practical Examples

If you are building a web scraper, you might add

with a specific constraint:

# Adds requests but restricts it to version 2.2x
poetry add requests@~2.2.0

Tips & Gotchas

Avoid manual edits to poetry.lock. Always let Poetry update this file via commands. If you encounter errors about a missing root folder during poetry install, use the --no-root flag if your current project isn't intended to be an installable package itself.

2 min read