This project acts as a boilerplate for a fully-featured, reproducible, Python development environment. Namely, it provides:
- Reproducible builds, packaging, and development environments with Nix
- Automatic integration of Python dependencies into the Nix ecosystem with Poetry and Poetry2nix.
- Event-based activation and deactivation of the development environment with direnv and nix-direnv.
- Automatic Python intepreter selection for execution and debugging in VSCode with using direnv's VSCode extension direnv-vscode.
- Sane defaults in terms of Python tooling that can easily be modified (
black
,isort
,autoflake
, andpytest
). - A standard project layout as per Kenneth Reitz's recommendations.
- Nix with flakes enabled.
- direnv, its shell hook, and
nix-direnv
installed. - VSCode with the
direnv-vscode
andpython
extensions.
- Clone this repository.
- Run
direnv allow
to activate the development environment.direnv
will load the environmentflake.nix
and populate the environment with the dependencies specified inpyproject.toml
. This will take a while the first time, but subsequent loads will be much faster asnix-direnv
will cache the environment. - Open the project in VSCode, and load the environment if prompted.
direnv-vscode
will automatically load the environment, and especially the$PYTHONPATH
variable, that VSCode will use to select the correct Python interpreter. - Profit!
Poetry manages the dependencies in pyproject.toml
, and will generate the lockfile poetry.lock
when you run poetry lock
.
Using poetry add <package>
will add the package to both files.
You can also edit manually pyproject.toml
and run poetry lock
to update the lockfile.
Direnv will automatically load the environment when you enter the project directory.
It will also rebuild the environment if flake.nix
or pyproject.toml
have changed.
If you want to force a rebuild, you can run direnv reload
.
One caveat of this setup is that an empty pyproject.toml
, an error in the syntax, or inconsistencies between pyproject.toml
and poetry.lock
will cause nix-direnv
to fail.
At that point, the Nix environment will not be loaded, and even poetry won't be available anymore (unless you have poetry installed globally).
To fix the issue, the flake provides a poetry distribution that is pinned to the same version as the one used in the environment.
You can use it to regenerate the lockfile or interact with poetry in general, via nix run .#poetry <args_or_subcommands>
.
For example, to regenerate the lockfile, run nix run .#poetry lock
.