Getting started with POETRY 
(the python dependency manager)

Getting started with POETRY (the python dependency manager)

An introduction to an intuitive python dependency management tool

ยท

2 min read

Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Poetry offers a lockfile to ensure repeatable installs, and can build your project for distribution.


INSTALL on Linux & macOS

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

VERIFY Installation

poetry --version

UPDATE Poetry itself

poetry self update

UNINSTALL Poetry

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

Setup NEW Project

poetry new poetry-demo

PS: poetry-demo should be the name of your project

...the command creates a directory poetry-demo with the following content:

poetry-demo
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ http://README.md
โ”œโ”€โ”€ poetry_demo
โ”‚   โ””โ”€โ”€ __init__.py
โ””โ”€โ”€ tests
    โ””โ”€โ”€ __init__.py

PS: pyproject.toml is the most important file here. And it looks like this:

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["JJOKAH <jjokah@example.com>"]
readme = "README.md"
packages = [{include = "poetry_demo"}]

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

[tool.poetry.dev-dependencies]
black = "^21.9b0"

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

INTIALISE a pre-existing project

cd pre-existing-project
poetry init

PS: this interactively creates a pyproject.toml file in the directory - pre-existing-project


SPECIFY and ADD dependencies

...in the pyproject.toml file under the tool.poetry.dependencies section, specify your package like this:

[tool.poetry.dependencies]
pendulum = "^2.1"

...OR use this command:

poetry add pendulum

VERSION constraints

...in the example above pendulum="^2.1" means install the pendulum package with a version greater than 2.1.0 and less than 3.0.0 (>=2.1.0 <3.0.0)


DEV dependencies

specify with --dev to add a package for the development environment only and not in Production:

poetry add black --dev

... black package will be added to the tool.poetry.dev-dependencies section

[tool.poetry.dev-dependencies]
black = "^21.9b0"

INSTALL dependencies

poetry install

UPDATE dependencies

poetry update

ACTIVATE the virtual environment

poetry shell

DEACTIVATE / exit the environment

exit

Now, we are all set with #python poetry ๐Ÿฅ‚.