Skip to content

Using Poetry and Pip with Nix Flakes

Pip

I have found that pip doesn't work globally, but as long as you always make a virtual environment for whatever you intend to install, it works great.

Add this to your home.nix

  home.packages = with pkgs; [
    # ..snip
    python310
    python310Packages.pip
];
  home.packages = with pkgs; [
    # ..snip
    python310
    python310Packages.pip
];

Now create a virtual env, source it, and install away. See here.

sh
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install pandas
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install pandas

Poetry

To outline the process of starting a new Python package with Nix and Poetry, we'll setup a client using the pika library.

Start by using the Flake template at the poetry2nix repository

nix flake init --template github:nix-community/poetry2nix
nix flake init --template github:nix-community/poetry2nix

Enter the Nix development environment and initialize the Poetry dependency manager. Optionally, you may setup your environment with direnv (see Using Nix Flakes).

nix develop
poetry init
nix develop
poetry init

Add dependencies to your project,

poetry add pika pillow
poetry add pika pillow

Your project tree should look something like

.
├── flake.lock
├── flake.nix
├── client
│   └── main.py
├── poetry.lock     # Pinned poetry dependencies
└── pyproject.toml  # Manifest file
.
├── flake.lock
├── flake.nix
├── client
│   └── main.py
├── poetry.lock     # Pinned poetry dependencies
└── pyproject.toml  # Manifest file

Setup a script in pyproject.toml for running your program

[tool.poetry]
name = "pika-client"
version = "0.1.0"
description = ""
authors = ["Braden Stefanuk"]
readme = "README.md"
packages = [{include = "client"}]

[tool.poetry.dependencies]
python = "^3.10"
pika = "^1.3.2"
pillow = "^10.0.0"

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

[tool.poetry.scripts]
start = "client.main:main"
[tool.poetry]
name = "pika-client"
version = "0.1.0"
description = ""
authors = ["Braden Stefanuk"]
readme = "README.md"
packages = [{include = "client"}]

[tool.poetry.dependencies]
python = "^3.10"
pika = "^1.3.2"
pillow = "^10.0.0"

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

[tool.poetry.scripts]
start = "client.main:main"

Now you can run your program (pending you have a main function in) client/main.py with

poetry run start
poetry run start
RESOUCES