Getting Started with Poetry for Python Dependency Management
What is Poetry?
Poetry is a powerful tool for managing Python virtual environments and dependencies. Beyond dependency management, it also offers package publishing capabilities. It serves as a unified solution for handling both Python libraries and applications.
Installing Poetry
Option 1 - Official installer:
curl -sSL https://install.python-poetry.org | python3 -
Option 2 - Using pip:
pip3 install poetry
Verify Installation
Check the installed version:
poetry --version
Setting Up Poetry in a Project
For Existing Projects:
Run the initialization command to generate a pyproject.toml file:
poetry init
Creating a New Project:
Generate a fresh project structure:
poetry new my_application
The project structure looks like this:
Structure Overview
- pyproject.toml: This configuration file handles dependency declarations and project metadata. It consolidates what traditionally required multiple files like Pipfile, requirements.txt, setup.py, setup.cfg, and MANIFEST.in.
Creating the Virtual Environment
Note: Ensure the current directory contains a pyproject.toml file before proceeding.
poetry install
This command reads all dependencies from pyproject.toml and installs them, including development dependencies. To skip development dependencies, add the --no-dev flag. If a poetry.lock file exists in the project root, it installs the locked versions. Running add or remove commands without an active virtual environment will automatically create one.
Activating the Virtual Environment
poetry shell
Checking the Python Version
poetry run python --version
Running Scripts
poetry run python main.py
Installing Packages
poetry add flask
To add as a development dependency, include the --dev flag:
poetry add pytest --dev
Viewing and Updating Packages
Display installed packages:
poetry show
Use the --tree flag to visualize dependency relationships:
poetry show --tree
Check for outdated dependencies:
poetry show --outdated
Update all dependencies to their latest compatible versions:
poetry update
Update a specific package:
poetry update requests
Removing Packages
poetry remove requests
Specifying the Python Interpreter
poetry env use python3.11
If you encounter issues where Poetry selects an incorrect Python version (unrelated to pyenv), this command ensures it uses the desired interpreter.
Common Configuration Tips
Q&A
1, Its recommended to use Python 3 exclusively
2, Poetry version compatibility is crucial - always use the latest stable release for the best experience