Using Nix to Create Python Virtual Environments

Nix and Python logos





We do this by managing Python and pip as Nix dependencies (as well as any any other Python packages we wish to have managed through Nix, for example those with system dependencies such as NumPy).

For example, create a in your project root as follows:

with import <nixpkgs> {};
  my-python-packages = python-packages: [
  my-python = python36.withPackages my-python-packages;
  pkgs.mkShell {
    buildInputs = [
    shellHook = ''
      export PIP_PREFIX="$(pwd)/_build/pip_packages"
      export PYTHONPATH="$(pwd)/_build/pip_packages/lib/python3.6/site-packages:$PYTHONPATH" 

Activate it in your shell by running $ nix-shell.

This makes available Python 3.6, pip and NumPy. Environment variable PIP_PREFIX tells pip to install its packages in subdirectory _build in your project root’s folder. PYTHONPATH is extended with the directory where this project’s pip will now install packages. These environment changes are necessary because this Python installation lives inside the read-only Nix store, and pip would not be able to install packages there.

Note that we unset SOURCE_DATE_EPOCH. Nix sets it to a value of 1 for reproducible builds, causing Python’s bdist_wheel to fail as it requires SOURCE_DATE_EPOCH to correspond to 1980 or later.

You can now use pip as you normally would, such as

$ pip install -r requirements.txt

One thought on “Using Nix to Create Python Virtual Environments

Leave a Reply

