• Getting Started with Python Poetry: Dependency Management and Publishing

    Introduction

    Python Poetry is a powerful tool for dependency management and packaging in Python. It simplifies package installation, dependency resolution, and publishing to PyPI. In this post, we’ll explore how to use Poetry, manage dependencies, understand versioning syntax, and publish a package.

    Installing Poetry

    To install Poetry, run the following command:

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

    After installation, add Poetry to your PATH:

    export PATH="$HOME/.local/bin:$PATH"
    

    To verify the installation, run:

    poetry --version
    

    Creating a New Project

    To create a new Python project with Poetry, use:

    poetry new my_project
    

    This creates a my_project directory with a predefined structure:

    my_project/
    ├── pyproject.toml
    ├── README.rst
    ├── my_project/
    │   └── __init__.py
    └── tests/
    

    Managing Dependencies

    Poetry simplifies dependency management using the pyproject.toml file.

    Adding Dependencies

    To add a dependency, use:

    poetry add requests
    

    This updates pyproject.toml and installs the dependency.

    Adding Development Dependencies

    For dependencies used in development (e.g., testing libraries like pytest), use:

    poetry add --dev pytest
    

    Installing Dependencies

    If you clone a project that uses Poetry, install dependencies with:

    poetry install
    

    This installs both main and development dependencies.

    Understanding Versioning in Poetry

    Poetry uses semantic versioning (SemVer) and supports flexible version constraints:

    • ^1.2.3: Compatible with 1.x.y, where x >= 2
    • ~1.2.3: Compatible with 1.2.x, but < 1.3.0
    • 1.2.3: Exact version 1.2.3
    • >=1.2, <2.0: Custom range

    Example:

    dependencies = {
        "requests" = "^2.25.1"
    }
    

    This allows any 2.x version, but not 3.x.

    Running Tests with Poetry

    After adding pytest as a development dependency, run tests with:

    poetry run pytest
    

    Publishing to PyPI

    To publish a package, follow these steps:

    1. Build the package:poetry build
    2. Publish to PyPI:poetry publish --username --password

    For automated publishing, use a PyPI token:

    poetry config pypi-token.pypi 
    poetry publish
    

    Conclusion

    Poetry is a modern tool that simplifies dependency management, versioning, and publishing. By using Poetry, you can ensure consistent environments, easily manage dependencies, and streamline package distribution.

Scroll to Top