WRITELOOP

USING POETRY FOR DEPENDENCIES ON PYTHON PROJECTS

2021 September 27

poetry

Setting up the environment to create a new poetry project

  • Poetry automatically creates virtual environments for your applications. So, it is best to be installed isolated from your application with e.g. pipx, to avoid it as a dependency on your development environment (e.g. pyenv):

  • Create the directory that will hold the project and enter it: mkdir <project-name> && cd $_

  • We will use pyenv to set on this directory the local Python version we are going to use (e.g. 3.9.1). This will prompt poetry to use the local version of Python defined by pyenv:

pyenv local 3.9.1

This will create a .python-version file inside the project. This file will be read by pyenv and prompts it to set the defined local Python version. Consequently every directory or file created down this point will depend on the local Python version and not the global one.

IMPORTANT: on a Dockerfile, I can use its' install script:

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

Creating a new project

  • Create a new python project from poetry: poetry new <project-name>.

IMPORTANT: You can also inject it into an existing project: poetry init

Other useful commands:

  • poetry shell: The first time this command is run in your project directory, Poetry creates a Python virtual environment which will forever be associated with this project. Once this virtual environment is created, it can be activated again at any time by simply running poetry shell in your project directory in the future.

  • poetry install: Installs the dependencies in pyproject.toml. The first time a project’s dependencies are installed, a .lock file is created, which contains the actual version numbers of each package that was installed. If a .lock file is present, the version numbers on it will always be prioritized over what is in pyproject.toml.

Here is a cheatsheet of mine with some more useful commands, explaining what each one of them do.

References: