Poetry is a powerful tool for Python developers that simplifies project management, dependency handling, and package distribution. It aims to solve common pain points in the Python ecosystem by providing a single, intuitive interface for managing your projects from start to finish.
pyproject.toml
file to declare dependencies, making it easy to specify and lock versions.To install Poetry, run the following command in your terminal:
curl -sSL https://install.python-poetry.org | python3 -
Verify the installation by running:
poetry --version
To create a new Python project with Poetry, use the new
command:
poetry new my-awesome-project
This creates a new directory with the following structure:
my-awesome-project/
├── pyproject.toml
├── README.md
├── my_awesome_project/
│ └── __init__.py
└── tests/
└── __init__.py
To add Poetry to an existing project, navigate to your project directory and run:
poetry init
This will guide you through creating a pyproject.toml
file interactively.
To add a new dependency to your project:
poetry add requests
This command adds the package to your pyproject.toml
file and installs it in your virtual environment.
Poetry allows you to specify version constraints for your dependencies:
[tool.poetry.dependencies] python = "^3.8" requests = "^2.25.1" numpy = ">=1.20,<2.0"
For packages only needed during development, use the --dev
flag:
poetry add pytest --dev
This adds the package to the [tool.poetry.dev-dependencies]
section in pyproject.toml
.
Poetry automatically creates and manages virtual environments for your projects.
To activate the virtual environment:
poetry shell
To run a command without activating the environment:
poetry run python your_script.py
To build your package:
poetry build
This creates both source and wheel distributions in the dist/
directory.
First, configure your PyPI credentials:
poetry config pypi-token.pypi your-token
Then, publish your package:
poetry publish
You can specify custom package sources in your pyproject.toml
:
[[tool.poetry.source]] name = "private" url = "https://private.pypi.org/simple/"
Define custom scripts in your pyproject.toml
:
[tool.poetry.scripts] my-command = "my_package.cli:main"
Generate a requirements.txt
file:
poetry export -f requirements.txt --output requirements.txt
pyproject.toml
clean: Regularly review and remove unused dependencies.poetry.lock
to ensure reproducible builds.By embracing Poetry in your Python projects, you'll streamline your workflow, improve dependency management, and simplify the packaging and distribution process. As you become more familiar with Poetry's features, you'll find it an invaluable tool in your Python development toolkit.
14/11/2024 | Python
15/01/2025 | Python
25/09/2024 | Python
08/12/2024 | Python
05/11/2024 | Python
26/10/2024 | Python
25/09/2024 | Python
14/11/2024 | Python
05/10/2024 | Python
15/01/2025 | Python
17/11/2024 | Python
06/10/2024 | Python