Add Nix to Python projects - as simple as possible

I’m asking for experience reports here. My situation is:

  • I’ve got multiple Python projects I would like to use Nix with. They have a setup.py and I’m currently using pip to install dependencies (as in pip install -e .[some-flags]).

  • Ideally, I would like to not write any custom Nix derivations for these projects and have one derived for me from the setup.py, or possibly from a requirements.txt or something similar. My goals would be:

  • Using direnv + nix-shell to auto-load a nice shell environment with all dependencies in place when I cd into the directory.

  • Package my application into a Docker container easily (possibly only one of the entry_points).

Is something like that possible? I saw that there is…

  • pypi2nix which has been abandoned
  • poetry2nix for which I would have to adopt poetry, a step I’d be willing to take if it really works.

Is there any…methodology or something I missed?

1 Like

I would take a look at https://github.com/NixOS/nixpkgs/blob/3d6adb6f7d62be1257808d055696a07dd3ec68f6/doc/languages-frameworks/python.section.md#how-to-consume-python-modules-using-pip-in-a-virtual-environment-like-i-am-used-to-on-other-operating-systems-how-to-consume-python-modules-using-pip-in-a-virtual-environment-like-i-am-used-to-on-other-operating-systems

Sounds like a good use case for GitHub - DavHau/mach-nix: Create highly reproducible python environments

See first reply, and just enable direnv

You probably will do something like:

  dockerTools.buildImage {
    ...
    contents = [ (python3Packages.toPythonApplication python3Packages.myPkg) ];
  }
3 Likes

That must be the best, most comprehensive answer I have ever received on a forum, thanks Jon! I’ll take a look at mach-nix and poetry2nix and see if one of them is what I wanted.

2 Likes

mach-nix with nix-flakes Example: https://github.com/GTrunSec/Coding-Dev-Env-With-NixFlake/blob/14340dc405871f1be5b5a4d50ea616c7923fe239/python/flake.nix