Simplifying Python Dependency Management with Poetry

Simplifying Python Dependency Management with Poetry

By Pulkit2 min read

Managing Python dependencies can be hard, especially as projects get bigger. It's important to have the right packages and versions installed without conflicts. Poetry helps with this. It's a tool that makes managing project dependencies, packaging, and publishing easier. In this article, we'll show you how to use Poetry to manage Python dependencies, make your workflow smoother, and keep your project setup clean and efficient.

In this blog, you will learn how to:

  • Install Poetry on your system

  • Create a new Poetry project

  • How to run fastapi server with poetry

Installing Poetry

Reference: python-poetry.org/docs/#installation

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

Blog image

Create a new Poetry Project

PLAINTEXT
poetry new awesome-project

This will create a fresh poetry project with a directory structure like this

Blog image

Pyproject.toml

Poetry manages all the dependencies with the help of the pyproject.toml, It is similar to the package.json in a node project

PLAINTEXT
[tool.poetry]
name = "awesome-project"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.12"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

Activate a virtual environment

You can list all the virtual environments available in poetry

PLAINTEXT
poetry shell

Blog image

Let's make a simple hello world FastAPI Server

Adding fastapi and uvicorn as dependencies

PLAINTEXT
poetry add fastapi uvicorn

Blog image

Now if you check the pyproject.toml, fastapi and uvicorn are added as dependencies

Blog image

Write a basic fastapi server

PYTHON
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

Blog image

To run the server lets start by using the following command

PLAINTEXT
poetry run uvicorn main:app --reload

Blog image

And as expected the server is in a good condition

Blog image

By following the steps outlined in this article, you can effectively manage your Python dependencies using Poetry. This powerful tool not only simplifies dependency management but also enhances your workflow, ensuring that your projects remain clean, efficient, and free from conflicts. Whether you're starting a new project or maintaining an existing one, Poetry provides the structure and reliability needed to keep your development process smooth and hassle-free. Happy coding!