Managing Python Packages with Poetry
Poetry is a robust tool for managing Python projects and their dependencies. It simplifies package management by handling dependency resolution, virtual environments, and publishing packages. This guide will walk you through using Poetry for Python package management, covering installation, project setup, dependency management, virtual environments, and package publishing.
Table of Contents
- Introduction to Poetry
- Installation
- Creating a New Project
- Managing Dependencies
- Virtual Environments
- Running Scripts and Commands
- Publishing Packages
- Additional Features
- Conclusion
Introduction to Poetry
Poetry is a dependency management and packaging tool for Python. It aims to simplify the process of managing project dependencies, virtual environments, and publishing packages. Key features include:
- Dependency Resolution: Automatically resolves and locks dependencies.
- Virtual Environments: Manages virtual environments per project.
- Project Management: Handles project setup, versioning, and publishing.
- Consistent Configuration: Uses a
pyproject.toml file for configuration, adhering to PEP 517 and PEP 518 standards.
Installation
Prerequisites
- Python 3.7+: Ensure you have Python installed. You can download it from python.org.
Installing Poetry
There are multiple ways to install Poetry. The recommended method is using the official installer via curl or pip.
Using the Official Installer (Recommended):
Open your terminal and run:
curl -sSL https://install.python-poetry.org | python3 -
Using pip:
Alternatively, you can install Poetry via pip:
pip install poetry
Verify Installation
After installation, verify that Poetry is installed correctly:
poetry --version
You should see output like:
Poetry (version 1.4.2)
Creating a New Project
Initialize a New Project
To create a new Python project with Poetry, use the poetry new command:
poetry new my_project
This will create a new directory my_project with the following structure:
my_project/
├── pyproject.toml
├── README.rst
├── my_project
│ └── __init__.py
└── tests
├── __init__.py
└── test_my_project.py
Existing Project Setup
If you have an existing project and want to manage it with Poetry, navigate to the project's root directory and run:
poetry init
This command guides you through creating a pyproject.toml file by interactively asking about dependencies.
Managing Dependencies
Poetry simplifies the process of adding, removing, and updating dependencies.
Adding Dependencies
To add a dependency to your project, use the poetry add command:
poetry add requests
This command does the following:
- Adds
requests to the [tool.poetry.dependencies] section in pyproject.toml.
- Installs the package in the project's virtual environment.
- Updates the
poetry.lock file with the resolved dependencies.
Specifying Dependency Versions:
You can specify version constraints:
poetry add requests@^2.25.1
Or using comparison operators:
poetry add "django>=3.0,<4.0"
Adding Development Dependencies
To add a dependency only needed for development (e.g., testing tools), use the --dev flag:
poetry add pytest --dev
This adds pytest to the [tool.poetry.dev-dependencies] section.
Removing Dependencies
To remove a dependency, use the poetry remove command:
poetry remove requests
This removes requests from pyproject.toml and updates the poetry.lock accordingly.
Updating Dependencies
To update all dependencies to their latest allowed versions based on pyproject.toml, run:
poetry update
To update a specific package:
poetry update requests
This updates only the requests package and its dependencies.
Listing Dependencies
To list all installed dependencies:
poetry show
For a tree view:
poetry show --tree
Virtual Environments
Poetry automatically manages virtual environments for each project, isolating dependencies.
Creating and Activating the Virtual Environment
When you run poetry install or add dependencies, Poetry creates a virtual environment. To activate it:
poetry shell
This opens a new shell within the virtual environment. To exit, simply type exit.
Running Commands Within the Virtual Environment
If you prefer not to activate the shell, you can run commands directly within the virtual environment using poetry run:
poetry run python script.py
Or, for example, to run pytest:
poetry run pytest
Configuring Virtual Environment Settings
You can configure Poetry to create virtual environments inside the project directory or elsewhere:
-
Inside the Project Directory:
poetry config virtualenvs.in-project true
This creates the virtual environment in .venv/ within the project directory.
-
Default Behavior (Outside Project Directory):
Poetry manages virtual environments in a centralized location, typically under ~/.cache/pypoetry/.
Running Scripts and Commands
Poetry allows you to define custom scripts and commands in the pyproject.toml under the [tool.poetry.scripts] section.
Defining a Script
For example, to define a script named my-script that runs my_project.main:
[tool.poetry.scripts]
my-script = "my_project.main:main"
Running the Script
After defining the script, you can run it using:
poetry run my-script
Publishing Packages
If you’re developing a package you want to distribute, Poetry streamlines the publishing process.
Configuring PyPI Credentials
First, configure your PyPI credentials:
poetry config pypi-token.pypi YOUR_PYPI_TOKEN
Replace YOUR_PYPI_TOKEN with your actual token from PyPI.
Building the Package
To build your package, run:
poetry build
This creates tar.gz and whl files in the dist/ directory.
Publishing the Package
To publish your package to PyPI:
poetry publish
If you configured the PyPI token, Poetry uses it automatically. Otherwise, it will prompt for your PyPI username and password.
Publishing to Test PyPI:
For testing purposes, you can publish to Test PyPI:
poetry publish --repository test-pypi
Ensure you have the Test PyPI repository configured in [tool.poetry.source] if necessary.
Versioning
Poetry adheres to semantic versioning. To update your project's version, use:
poetry version patch # Increments the patch version (e.g., 1.0.0 → 1.0.1)
poetry version minor # Increments the minor version (e.g., 1.0.0 → 1.1.0)
poetry version major # Increments the major version (e.g., 1.0.0 → 2.0.0)
You can also set a specific version:
poetry version 1.2.3
Additional Features
Dependency Groups
Poetry 1.2+ supports dependency groups, allowing for more granular dependency management (e.g., optional features).
Defining Dependency Groups:
poetry add --group dev flake8
This adds flake8 to the [tool.poetry.group.dev.dependencies] section.
Installing with Specific Groups:
poetry install --with dev
Excluding Specific Groups:
poetry install --without dev
Lock File
poetry.lock ensures deterministic builds by locking the exact versions of dependencies.
-
Updating the Lock File:
poetry lock
-
Regenerating the Lock File:
If you suspect corruption or want to regenerate:
rm poetry.lock
poetry lock
Scripts and Plugins
You can extend Poetry's functionality using plugins or define custom scripts as needed.
Best Practices
- Use Virtual Environments: Let Poetry manage your project's virtual environment for isolation.
- Commit
pyproject.toml and poetry.lock: Ensure both files are version-controlled for reproducible environments.
- Semantic Versioning: Follow semantic versioning to manage package versions effectively.
- Regular Updates: Periodically update dependencies to incorporate bug fixes and security patches using
poetry update.
- Use Dependency Groups: Organize dependencies into groups (e.g., dev, test) for better manageability.
Conclusion
Poetry offers a comprehensive and user-friendly approach to Python package management, handling dependencies, virtual environments, and packaging seamlessly. By integrating Poetry into your workflow, you can enhance productivity, ensure consistency across environments, and simplify the deployment and distribution of your Python projects.
For more detailed information, refer to the official Poetry documentation.