Python: Setting up the environment

Theory: Building a package distribution using Poetry

When your project is ready to be shared with others, it's time to build the code. The compiled distribution doesn't need Poetry anymore. The program will run without it.

It is where Poetry comes in again. In this tutorial, we'll learn how to build and install the distribution.

Building and installing the distribution kit

Usually, Poetry projects are almost ready to build their distributions. Some cases require additional configuration steps. But we won't go into that because it's irrelevant.

You can build a simple project using the poetry build command:

poetry build

Building hello (0.1.0)
  - Building sdist
  - Built hello-0.1.0.tar.gz
  - Building wheel
  - Built hello-0.1.0-py3-none-any.whl

Run this command in the root directory of the project. You will see a dist/ directory with two files with different extensions.

First, we look at a file with the .whl extension, which is short for wheel. This file is already suitable for installation using pip. Let's install it in the user's environment:

python3 -m pip install --user dist/hello-0.1.0-py3-none-any.whl

Processing ./dist/hello-0.1.0-py3-none-any.whl
Installing collected packages: hello
Successfully installed hello-0.1.0

If there are scripts described for the project, they're available as commands. For example, this is how say-hello works in our case:

say-hello

Hello!

Installing the package without building the distribution

When you work on code, you often want to try out your project quickly and without too much effort.

Let's try running the program without building a distribution. To do this, specify the path to the project directory as the package name in the pip install command:

python3 -m pip install .

Processing /.../hello
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Building wheels for collected packages: hello
  Building wheel for hello (PEP 517) ... done
  Created wheel for hello: filename=hello-0.1.0-py3-none-any.whl size=1671
...
Successfully built hello
Installing collected packages: hello
Successfully installed hello-0.1.0

say-hello

Hello!

In the code above, we used the dot . — if you remember, that means the current directory.

Installing Poetry projects from GitHub

This course mentioned earlier that you can install packages directly from GitHub using pip. This feature is also available for poetry projects.

Pip has only recently become aware of pyproject.toml. We recommend that you upgrade pip regularly with the pip install --user --upgrade pip command.