Poetry is a Python dependency management and packaging tool, designed to be user-friendly and intuitive, while ensuring consistency and reproducibility in projects.
Before diving into the commands, ensure you've installed Poetry:
curl -sSL https://install.python-poetry.org | python3 -
Or using pip (though the above method is recommended):
pip install poetry
poetry new project-name
This command creates a new directory project-name
with a basic project structure.
poetry add package-name
This command adds a package to your project. Poetry will automatically update the pyproject.toml
and poetry.lock
files.
For development-only dependencies (like testing libraries):
poetry add package-name --dev
poetry remove package-name
This will remove the package and update the necessary files.
If you have an existing pyproject.toml
and poetry.lock
file (e.g., after cloning a repo):
poetry install
This command reads the poetry.lock
file to ensure consistent installations across environments.
To build your project:
poetry build
This produces distribution packages (wheel and sdist) that can be published to PyPI.
To publish to PyPI:
poetry publish --build
Ensure you're authenticated to PyPI before publishing.
You can define custom scripts in pyproject.toml
:
[tool.poetry.scripts]
script-name = "module:function"
Run the script using, this will run in poetry Virtual Environment
poetry run script-name
To update a specific package and simultaneously refresh both the poetry.lock
and pyproject.toml
files:
poetry update package-name
To update all packages and refresh the poetry.lock
:
poetry update
If you've manually updated the pyproject.toml
but not the poetry.lock
:
- Delete
poetry.lock
and then run:
poetry install
This will regenerate the poetry.lock
file.
- Alternatively, you can refresh all packages and the
poetry.lock
with:
poetry update
- If you want to regenerate the lock file without updating packages:
poetry lock --no-update
To list all dependencies and their details:
poetry show
Poetry creates a virtual environment for your projects by default. You can access the environment using:
poetry shell
To check if pyproject.toml
is valid:
poetry check
Poetry is a robust tool that makes dependency management and packaging seamless. With its deterministic builds, it ensures that projects are consistent across all environments. Get started, and enjoy a better Python packaging experience!