Last active
March 11, 2025 15:33
-
-
Save blockloop/f37c96710d492aecdc129df69bd37842 to your computer and use it in GitHub Desktop.
shell.nix+direnv for python/uv/poetry using python version from pyproject.toml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
if ! has nix_direnv_version || ! nix_direnv_version 3.0.6; then | |
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.6/direnvrc" "sha256-RYcUJaRMf8oF5LznDrlCXbkOQrywm0HDv1VjYGaJGdM=" | |
fi | |
use nix |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
pkgs ? import <nixpkgs> { }, | |
}: | |
let | |
# read Python version from pyproject.toml | |
pyproject = builtins.fromTOML (builtins.readFile ./pyproject.toml); | |
pythonVersionFull = | |
pyproject.project."requires-python" or pyproject.tool.poetry.dependencies.python | |
or pkgs.python3.version; | |
# parse out the version | |
pythonVersion = builtins.head (builtins.match ''[^\d]*([0-9]+\.[0-9]+).*'' pythonVersionFull); | |
# package version is python<major><minor> e.g. python313 for 3.13 | |
pythonPackageVersion = | |
let | |
parts = builtins.splitVersion pythonVersion; | |
major = builtins.elemAt parts 0; | |
minor = builtins.elemAt parts 1; | |
in | |
"${major}${minor}"; | |
python = pkgs."python${pythonPackageVersion}"; | |
# bin wrappers for tools | |
poetryWrapped = pkgs.writeScriptBin "poetry" '' | |
#!${pkgs.bash}/bin/bash | |
exec ${pkgs.uv}/bin/uvx poetry "$@" | |
''; | |
lib = pkgs.lib; | |
in | |
pkgs.mkShell { | |
buildInputs = [ | |
poetryWrapped | |
python | |
pkgs.pyright | |
pkgs.uv | |
]; | |
env = | |
{ | |
PYTHON_VERSION = pythonVersion; | |
UV_PYTHON = "${builtins.toString ./.}/.direnv/nix-shell/python-${pythonVersion}/python"; | |
PATH = "${builtins.toString ./.}/.venv/bin:${builtins.toString ./.}/.direnv/nix-shell/python-${pythonVersion}:$PATH"; | |
} | |
// lib.optionalAttrs pkgs.stdenv.isLinux { | |
# Python libraries often load native shared objects using dlopen(3). | |
# Setting LD_LIBRARY_PATH makes the dynamic library loader aware of libraries without using RPATH for lookup. | |
LD_LIBRARY_PATH = lib.makeLibraryPath pkgs.pythonManylinuxPackages.manylinux1; | |
}; | |
shellHook = '' | |
unset PYTHONPATH | |
''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment