Dependency Management with Poetry

Loading

Poetry is a modern dependency management and package building tool for Python. It simplifies handling dependencies, virtual environments, and publishing packages.


1. Why Use Poetry?

Simple Dependency Management – Automatically manages dependencies and virtual environments.
Better than pip and requirements.txt – Uses pyproject.toml for configuration.
Built-in Package Publishing – Easily publish packages to PyPI.
Faster and More Reliable – Resolves dependencies efficiently.


2. Installing Poetry

2.1 Install Poetry (Windows, macOS, Linux)

Run the official installer:

curl -sSL https://install.python-poetry.org | python3 -

For Windows, use PowerShell:

(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -

2.2 Verify Installation

poetry --version

Example Output:

Poetry 1.5.1

3. Creating a New Poetry Project

Run the following command:

poetry new my_project

This creates a project structure like:

my_project/
│── my_project/ # Package directory
│ │── __init__.py # Marks it as a package
│── tests/ # Test cases
│── pyproject.toml # Project configuration
│── README.rst # Documentation

3.1 Navigate into the Project Directory

cd my_project

4. Managing Dependencies

4.1 Adding a Dependency

poetry add requests

This installs the requests library and updates pyproject.toml.

4.2 Installing Dependencies

To install all dependencies in a project:

poetry install

4.3 Removing a Dependency

poetry remove requests

4.4 Listing Installed Dependencies

poetry show

5. Managing Virtual Environments

5.1 Check Poetry’s Virtual Environment

poetry env info

5.2 Activate Virtual Environment

poetry shell

This creates and activates a virtual environment.

5.3 Deactivate Virtual Environment

exit

6. Running Scripts with Poetry

Instead of activating the virtual environment manually, run scripts using:

poetry run python script.py

7. Managing Project Versions

7.1 Check the Current Version

poetry version

7.2 Update Project Version

shCopyEditpoetry version 1.1.0

8. Publishing a Package to PyPI

8.1 Build the Package

poetry build

This creates dist/my_project-0.1.0.tar.gz and .whl.

8.2 Upload to TestPyPI

poetry publish --repository testpypi

8.3 Upload to PyPI

poetry publish --username your-username --password your-password

9. Summary

CommandDescription
poetry new my_projectCreate a new Poetry project
poetry add package_nameAdd a dependency
poetry installInstall dependencies
poetry remove package_nameRemove a dependency
poetry showList installed dependencies
poetry shellActivate the virtual environment
poetry run python script.pyRun a script using Poetry
poetry versionCheck project version
poetry buildBuild the package
poetry publishPublish to PyPI

Leave a Reply

Your email address will not be published. Required fields are marked *