### Create Virtual Environments with uv2nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Demonstrates how to generate a virtual environment using default dependency presets or by explicitly defining package dependencies. ```nix pythonSet.mkVirtualEnv "hello-world-env" workspace.deps.default pythonSet.mkVirtualEnv "hello-world-env" { # Install hello-world with no enabled extras hello-world = [ ]; } ``` -------------------------------- ### Configure Editable Development Environments Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Shows how to create an editable overlay and package set, allowing local source changes to be reflected immediately without rebuilding. ```nix editableOverlay = workspace.mkEditablePyprojectOverlay { # Use environment variable pointing to editable root directory root = "$REPO_ROOT"; }; editablePythonSet = pythonSet.overrideScope editableOverlay; virtualenv = editablePythonSet.mkVirtualEnv "hello-world-dev-env" workspace.deps.all; ``` -------------------------------- ### Initialize Nix and uv projects Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Commands to initialize a Nix flake template or a new uv Python project. These commands set up the necessary boilerplate files like pyproject.toml and uv.lock. ```bash nix flake init --template github:pyproject-nix/pyproject.nix#impure nix flake init --template github:pyproject-nix/uv2nix#hello-world nix-shell -p python3 uv uv init --app --package uv lock ``` -------------------------------- ### Construct Python environment with uv2nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Steps to load a uv workspace, create a package overlay from uv.lock, and compose the final Python package set. This integrates build systems and project-specific dependencies into a unified Nix set. ```nix pythonBase = pkgs.callPackage pyproject-nix.build.packages { inherit python; }; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; overlay = workspace.mkPyprojectOverlay { sourcePreference = "wheel"; }; pythonSet = pythonBase.overrideScope ( lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel overlay ] ); ``` -------------------------------- ### Python Project Configuration (pyproject.toml) Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/hello-world.md This pyproject.toml file defines a basic Python project, including its name and version. It's used in conjunction with uv2nix to manage dependencies. ```toml [project] name = "hello-world" version = "0.1.0" ``` -------------------------------- ### Nix Flake Configuration (flake.nix) Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/hello-world.md This Nix flake configuration sets up a project using uv2nix. It defines how to build a package set from a uv.lock file and provides development shell environments. ```nix { description = "A Uv workspace setup using uv2nix"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; flake-utils.url = "github:numtide/flake-utils"; uv2nix.url = "github:nix-community/uv2nix"; }; outputs = { self = { ... }: flake-utils.lib.eachDefaultSystem (system: { packages = { # This package set is built from uv.lock # and can be built using `nix build .#packages..default` default = uv2nix.packages.${system}.default; }; devShells = { # Development shell using nix to manage virtual environments # Dependencies are installed in editable mode. # Enter this shell with `nix develop .#uv2nix` uv2nix = uv2nix.devShells.${system}.default; # Development shell using uv to manage virtual environments # Enter this shell with `nix develop .#impure` impure = uv2nix.devShells.${system}.impure; }; }); }; } ``` -------------------------------- ### Integrate Virtual Environments into Nix Shell Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Provides a configuration for mkShell to utilize the generated virtual environment, including necessary environment variables to prevent uv from managing its own state. ```nix pkgs.mkShell { packages = [ virtualenv pkgs.uv ]; env = { UV_NO_SYNC = "1"; UV_PYTHON = editablePythonSet.python.interpreter; UV_PYTHON_DOWNLOADS = "never"; }; shellHook = '' unset PYTHONPATH export REPO_ROOT=$(git rev-parse --show-toplevel) ''; } ``` -------------------------------- ### Install uv2nix using Classic Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/install.md This snippet shows how to import uv2nix and its dependencies (pyproject-nix, build-system-pkgs) using classic Nix. It fetches the Git repositories for each project and makes them available in the Nix environment. This method is useful for users who prefer not to use Nix Flakes. ```nix let pkgs = import { }; inherit (pkgs) lib; pyproject-nix = import (builtins.fetchGit { url = "https://github.com/pyproject-nix/pyproject.nix.git"; }) { inherit lib; }; uv2nix = import (builtins.fetchGit { url = "https://github.com/pyproject-nix/uv2nix.git"; }) { inherit pyproject-nix lib; }; pyproject-build-systems = import (builtins.fetchGit { url = "https://github.com/pyproject-nix/build-system-pkgs.git"; }) { inherit pyproject-nix uv2nix lib; }; in ... ``` -------------------------------- ### Nix: Augment install behavior with pyprojectHook Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/dist.md This Nix snippet shows how to augment the install behavior of a Python package by overriding the `pyprojectHook` with `pythonSet.pyprojectDistHook`. This installs the wheel into the build output directory but bypasses regular `pyproject.nix` install steps, making it unsuitable for `mkVirtualEnv`. ```nix pythonSet.hello-world.override { pyprojectHook = pythonSet.pyprojectDistHook; } ``` -------------------------------- ### Example Python Script with Inline Metadata Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/inline-metadata.md A sample Python script demonstrating the use of inline metadata for dependency management. This file serves as the target for the uv2nix build process. ```python {{#include ../../../templates/inline-metadata/scripts/example.py}} ``` -------------------------------- ### Configure Python interpreter in Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/getting-started.md Methods to select a Python interpreter for the project. You can either filter nixpkgs based on project requirements or explicitly define the interpreter. ```nix python = lib.head (pyproject-nix.lib.util.filterPythonInterpreters { inherit (workspace) requires-python; inherit (pkgs) pythonInterpreters; }); python = pkgs.python3; ``` -------------------------------- ### Expose Nixpkgs wheels to uv via UV_FIND_LINKS Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/nixpkgs-wheels.md Uses a symlink join to expose a nixpkgs package wheel to uv. The shellHook sets the UV_FIND_LINKS environment variable, allowing uv to discover and install the package locally. ```nix let python = pkgs.python3; uv-links = pkgs.symlinkJoin { name = "uv-links"; paths = [ python.pkgs.seccomp.dist ]; }; in mkShell { packages = [ pkgs.uv python ]; shellHook = '' ln -sfn ${uv-links} .uv-links export UV_FIND_LINKS=$(realpath -s .uv-links) ''; } ``` -------------------------------- ### Override package sources for Flake evaluation Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/nixpkgs-wheels.md Demonstrates how to override package attributes to ensure sources are correctly resolved during Flake evaluation when using local symlinks. ```nix let pyprojectOverrides = final: prev: { seccomp = prev.seccomp.overrideAttrs(old: { buildInputs = (old.buildInputs or []) ++ python.pkgs.seccomp.buildInputs; src = python.pkgs.seccomp.dist; }); }; in ... ``` -------------------------------- ### Create Editable Python Development Environments Source: https://context7.com/pyproject-nix/uv2nix/llms.txt The `mkEditablePyprojectOverlay` function generates a Nix overlay that installs local Python packages in editable mode. This allows source code changes to be reflected immediately without rebuilding the entire environment, ideal for development workflows. It can be configured to make specific packages editable or use an environment variable for the root directory. ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; pythonBase = (pkgs.callPackage pyproject-nix.build.packages { python = pkgs.python312; }).overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel (workspace.mkPyprojectOverlay { sourcePreference = "wheel"; }) ] ); # Create editable overlay editableOverlay = workspace.mkEditablePyprojectOverlay { # Use environment variable for editable root (resolved at shell entry) root = "$REPO_ROOT"; # Optional: Only make specific packages editable # members = [ "my-package" ]; }; # Apply editable overlay for development editablePythonSet = pythonBase.overrideScope editableOverlay; devVirtualenv = editablePythonSet.mkVirtualEnv "dev-env" workspace.deps.all; in { devShells.x86_64-linux.default = pkgs.mkShell { packages = [ devVirtualenv pkgs.uv ]; env = { UV_NO_SYNC = "1"; # Prevent uv from managing venv UV_PYTHON = editablePythonSet.python.interpreter; UV_PYTHON_DOWNLOADS = "never"; # Use Nix-provided Python }; shellHook = '' unset PYTHONPATH export REPO_ROOT=$(git rev-parse --show-toplevel) ''; }; }; } ``` -------------------------------- ### Nix: Add 'dist' output for wheels Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/dist.md This snippet demonstrates how to add a separate 'dist' output to a Nix package derivation using `overrideAttrs`. This allows the produced wheel files to be installed into a dedicated output directory, mirroring the behavior of `uv build`. ```nix pythonSet.hello-world.overrideAttrs (final: prev: { outputs = [ "out" "dist" ]; }) ``` -------------------------------- ### Integrate prebuilt nixpkgs packages via pyproject.nix hacks Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/nixpkgs-wheels.md Uses the hacks.nixpkgsPrebuilt utility to incorporate a nixpkgs package directly into a pyproject.nix virtual environment without requiring uv to discover it via links. ```nix let pyprojectOverrides = final: prev: { seccomp = hacks.nixpkgsPrebuilt { from = python.pkgs.seccomp; }; }; pythonSet' = pythonSet.overrideScope pyprojectOverrides; in pythonSet.mkVirtualEnv "seccomp-env" { seccomp = [ ]; } ``` -------------------------------- ### Create deployable applications with mkApplication Source: https://context7.com/pyproject-nix/uv2nix/llms.txt Shows how to use mkApplication to package a Python project for deployment. This approach isolates the application from the underlying virtual environment, exposing only necessary files like binaries and man pages. ```nix default = mkApplication { venv = pythonSet.mkVirtualEnv "app-env" workspace.deps.default; package = pythonSet.my-package; }; ``` -------------------------------- ### Construct dummy sources for minimal rebuilds Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/source-filtering.md Creates a minimal source directory using pkgs.runCommand to ensure the build environment only contains the absolute minimum files required. This is an alternative to fileset filtering for further reducing rebuild frequency. ```nix app = prev.app.overrideAttrs(old: { src = pkgs.runCommand "app-src" {} '' cp ${./pyproject.toml} pyproject.toml mkdir app touch app/__init__.py ''; }); ``` -------------------------------- ### Load uv Workspace with uv2nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt Loads a uv Python workspace from a project root directory using `uv2nix.lib.workspace.loadWorkspace`. It parses `pyproject.toml` and `uv.lock` files, discovers workspace members, and returns a workspace object. Configuration options like `compile-bytecode`, `no-binary`, and `no-build` can be overridden. ```nix { inputs = { nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; pyproject-nix.url = "github:pyproject-nix/pyproject.nix"; uv2nix.url = "github:pyproject-nix/uv2nix"; pyproject-build-systems.url = "github:pyproject-nix/build-system-pkgs"; }; outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; # Load workspace from current directory workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; # Optional: Override inferred configuration config = { compile-bytecode = true; no-binary = false; no-build = false; }; }; # Access workspace attributes # workspace.config - Loaded configuration # workspace.requires-python - Python version constraints # workspace.deps.default - Default dependencies # workspace.deps.all - All dependencies including optional/dev # workspace.deps.optionals - Only optional dependencies # workspace.deps.groups - Only dependency groups in { }; } ``` -------------------------------- ### Add Meta Attributes to Nix Virtual Environments Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/meta.md This Nix code snippet demonstrates how to override virtual environment derivations to add `meta` attributes. It shows how to pass through tests and set `meta.mainProgram` for external discoverability and command execution. ```nix { # Expose Python virtual environments as packages. packages = forAllSystems ( system: let pythonSet = pythonSets.${system}; # Add metadata attributes to the virtual environment. # This is useful to inject meta and other attributes onto the virtual environment derivation. # # See # - https://nixos.org/manual/nixpkgs/unstable/#chap-passthru # - https://nixos.org/manual/nixpkgs/unstable/#chap-meta addMeta = drv: drv.overrideAttrs (old: { # Pass through tests from our package into the virtualenv so they can be discovered externally. passthru = lib.recursiveUpdate (old.passthru or { }) { inherit (pythonSet.testing.passthru) tests; }; # Set meta.mainProgram for commands like `nix run`. # https://nixos.org/manual/nixpkgs/stable/#var-meta-mainProgram meta = (old.meta or { }) // { mainProgram = "hello"; }; }); in { default = addMeta (pythonSet.mkVirtualEnv "testing-env" workspace.deps.default); full = addMeta (pythonSet.mkVirtualEnv "testing-env-full" workspace.deps.all); } }) ``` -------------------------------- ### Create Pyproject Overlay with uv2nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt Generates a Nix overlay from a workspace's `uv.lock` file using `workspace.mkPyprojectOverlay`. This overlay can be applied to pyproject.nix's build infrastructure to make locked packages available. It supports source preference ('wheel' or 'sdist') and optional environment customizations. ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; python = pkgs.python312; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; # Create overlay from uv.lock overlay = workspace.mkPyprojectOverlay { # Choose source preference: "wheel" or "sdist" sourcePreference = "wheel"; # Optional: PEP-508 environment customizations environ = { }; # Optional: Specify dependencies for conflict resolution dependencies = workspace.deps.default; }; # Create base Python set pythonBase = pkgs.callPackage pyproject-nix.build.packages { inherit python; }; # Compose overlays into final package set pythonSet = pythonBase.overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel overlay ] ); # pythonSet now contains all packages from uv.lock # Access individual packages: pythonSet.requests, pythonSet.flask, etc. in { packages.x86_64-linux.default = pythonSet.mkVirtualEnv "my-env" workspace.deps.default; }; } ``` -------------------------------- ### Override build systems for cross-compilation Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/cross/index.md Demonstrates how to override build systems for both the build host and the target host. This is necessary to ensure the correct toolchains are utilized during the cross-compilation process. ```nix {{#include ./build-systems.nix}} ``` -------------------------------- ### Implement manual build system overrides with Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/overriding-build-systems.md A Nix overlay strategy to declaratively manage build system overrides for multiple packages. This approach simplifies the process of defining nativeBuildInputs and resolving build systems compared to manual per-package configuration. ```nix { buildSystemOverrides = final: prev: { # Example of overriding build systems for specific packages package-name = prev.package-name.overrideAttrs (old: { nativeBuildInputs = (old.nativeBuildInputs or []) ++ [ final.some-build-tool ]; }); }; } ``` -------------------------------- ### Override Python Packages for Wheel Builds in Nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt This snippet demonstrates how to override Python packages for binary wheel builds in Nix. It ensures that packages like `numba`, `opencv-python`, and `torch` have the necessary system libraries (e.g., `tbb_2021_11`, `libGL`, `glib`, `cudatoolkit`, `cudnn`) linked for `autoPatchelfHook`. ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; # Override for wheel builds pyprojectOverrides = _final: prev: { # numba requires a specific version of TBB numba = prev.numba.overrideAttrs (old: { buildInputs = (old.buildInputs or [ ]) ++ [ pkgs.tbb_2021_11 ]; }); # OpenCV wheel needs system libraries opencv-python = prev.opencv-python.overrideAttrs (old: { buildInputs = (old.buildInputs or [ ]) ++ [ pkgs.libGL pkgs.glib ]; }); # PyTorch with CUDA support torch = prev.torch.overrideAttrs (old: { buildInputs = (old.buildInputs or [ ]) ++ [ pkgs.cudaPackages.cudatoolkit pkgs.cudaPackages.cudnn ]; }); }; pythonSet = (pkgs.callPackage pyproject-nix.build.packages { python = pkgs.python312; }).overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel (workspace.mkPyprojectOverlay { sourcePreference = "wheel"; }) pyprojectOverrides ] ); in { packages.x86_64-linux.default = pythonSet.mkVirtualEnv "app-env" workspace.deps.default; }; } ``` -------------------------------- ### Apply Patch to Python Dependency in Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/patching-deps.md Demonstrates how to use a Nix overlay to apply a patch file to a specific Python package. This process requires the package to be built from an sdist, necessitating an explicit build system definition. ```diff {{#include ../../../dev/arpeggio.patch}} ``` ```nix {{#include ../../../dev/patching-deps.nix}} ``` -------------------------------- ### Build Python Virtual Environments with mkVirtualEnv Source: https://context7.com/pyproject-nix/uv2nix/llms.txt The `mkVirtualEnv` function from uv2nix creates a Nix derivation for a Python virtual environment. It aggregates specified Python packages and their dependencies, allowing for reproducible environments. You can define environments using dependency presets or by manually specifying packages and their extras. ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; pythonSet = (pkgs.callPackage pyproject-nix.build.packages { python = pkgs.python312; }).overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel (workspace.mkPyprojectOverlay { sourcePreference = "wheel"; }) ] ); in { packages.x86_64-linux = { # Using dependency presets default = pythonSet.mkVirtualEnv "app-env" workspace.deps.default; full = pythonSet.mkVirtualEnv "app-full-env" workspace.deps.all; # Manual dependency specification custom = pythonSet.mkVirtualEnv "custom-env" { # Package name with list of extras to enable my-package = [ ]; # No extras requests = [ "security" "socks" ]; # With extras }; }; }; } ``` -------------------------------- ### Create Nix Application Derivation with mkApplication Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/applications.md This Nix code snippet demonstrates how to use the `mkApplication` utility from `pyproject.nix` to create a Nix derivation for a Python application. It wraps a virtual environment (`venv`) and specifies the application's package, effectively abstracting the virtual environment details from the final Nix package. This ensures only necessary application components are included. ```nix { packages = forAllSystems ( system: let pythonSet = pythonSets.${system}; pkgs = nixpkgs.legacyPackages.${system}; inherit (pkgs.callPackages pyproject-nix.build.util { }) mkApplication; in { # Create a derivation that wraps the venv but that only links package # content present in pythonSet.hello-world. # # This means that files such as: # - Python interpreters # - Activation scripts # - pyvenv.cfg # # Are excluded but things like binaries, man pages, systemd units etc are included. default = mkApplication { venv = pythonSet.mkVirtualEnv "application-env" workspace.deps.default; package = pythonSet.hello-world; }; } ``` -------------------------------- ### Configure Nix Shell for Editable Builds with uv2nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/advanced-build-systems.md This Nix configuration sets up a development shell that includes 'uv' and the 'build-editable' package. It configures environment variables for 'uv' and defines a 'shellHook' to unset PYTHONPATH, set the repository root, and trigger the 'build-editable' command. This is crucial for build systems that perform in-place compilation of native extensions. ```nix pkgs.mkShell { packages = [ virtualenv pkgs.uv # Add build-editable package from pyproject.nix pyproject-nix.packages.${system}.build-editable ]; env = { UV_NO_SYNC = "1"; UV_PYTHON = python.interpreter; UV_PYTHON_DOWNLOADS = "never"; }; shellHook = '' unset PYTHONPATH export REPO_ROOT=$(git rev-parse --show-toplevel) # Re-run editable package build for side effects build-editable ''; }; ``` -------------------------------- ### Nix: Build sdists instead of wheels Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/dist.md This Nix snippet illustrates how to configure the build process to produce a source distribution (sdist) instead of a wheel. It achieves this by overriding the `uvBuildType` attribute to 'sdist' within the package derivation. ```nix (pythonSet.hello-world.override { pyprojectHook = pythonSet.pyprojectDistHook; }).overrideAttrs(old: { env.uvBuildType = "sdist"; }) ``` -------------------------------- ### Define Project Dependencies in pyproject.toml Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/testing.md Specifies the project configuration and dependencies required for the build and test environment. This file is used by uv2nix to generate the corresponding Nix derivations. ```toml {{#include ./testing/pyproject.toml}} ``` -------------------------------- ### Add native build dependencies Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/cross/index.md Shows the configuration pattern for adding native build dependencies to a project. These dependencies are required during the build phase on the build host. ```nix {{#include ./build-depends.nix}} ``` -------------------------------- ### Configure Dependency Conflicts with mkPyprojectOverlay Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/conflicts.md This snippet demonstrates how to define a package overlay in Nix to resolve dependency conflicts. It uses the workspace.mkPyprojectOverlay function to specify source preferences and map packages to their required extras. ```nix workspace.mkPyprojectOverlay { sourcePreference = "wheel"; dependencies = { hello-world = [ "extra1" ]; }; } ``` -------------------------------- ### Filter sources using Nix fileset API Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/source-filtering.md Uses the lib.fileset API to explicitly include only necessary files like pyproject.toml and package initialization files. This reduces unnecessary rebuilds by ignoring irrelevant project files. ```nix app = prev.app.overrideAttrs (old: { src = lib.fileset.toSource rec { root = ./.; fileset = lib.fileset.unions [ (root + "/pyproject.toml") (root + "/app/__init__.py") ]; }; }); ``` -------------------------------- ### Implement package tests using passthru.tests in Nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt Demonstrates how to add a test derivation to a Python package's passthru attribute. This allows integration with Nix flake checks by creating a virtual environment with test dependencies and executing pytest. ```nix pyprojectOverrides = final: prev: { my-package = prev.my-package.overrideAttrs (old: { passthru = old.passthru // { tests = (old.tests or { }) // { pytest = pkgs.stdenv.mkDerivation { name = "${final.my-package.name}-pytest"; inherit (final.my-package) src; nativeBuildInputs = [ (final.mkVirtualEnv "test-env" { my-package = [ "test" ]; }) ]; dontConfigure = true; buildPhase = '' runHook preBuild pytest --cov tests --cov-report html runHook postBuild ''; installPhase = '' runHook preInstall mv htmlcov $out runHook postInstall ''; }; }; }; }); }; ``` -------------------------------- ### Configure Nix Flake for Inline Metadata Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/usage/inline-metadata.md The flake.nix file defines the project structure, importing the necessary uv2nix modules to handle locked script dependencies. It enables building and running individual scripts defined in the project directory. ```nix {{#include ../../../templates/inline-metadata/flake.nix}} ``` -------------------------------- ### Override source fetching in Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/private-deps.md Uses Nix overrides to inject curl options and SSL certificates into the fetcher, enabling the use of a netrc file for authenticated downloads. ```nix let pyprojectOverrides = _final: prev: { iniconfig = prev.iniconfig.overrideAttrs(old: { src = old.src.overrideAttrs(_: { # Make curl use our netrc file. curlOpts = "--netrc-file /etc/nix/netrc"; # By default pkgs.fetchurl will fetch _without_ TLS verification for reproducibility. # Since we are transferring credentials we want to verify certificates. SSL_CERT_FILE = "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"; }); }); }; in ... ``` -------------------------------- ### Override Linux kernel version for marker evaluation Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/platform-quirks.md Shows how to specify a custom platform_release in the mkPyprojectOverlay environment settings. This allows for accurate PEP-508 marker evaluation when the target Linux kernel version differs from the host environment. ```nix let overlay = workspace.mkPyprojectOverlay { sourcePreference = "wheel"; environ = { platform_release = "5.10.65"; }; } in ... ``` -------------------------------- ### Override Wheel Builds with Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/overriding/index.md This Nix code snippet illustrates how to override pre-built binary (wheel) builds. This is a workaround for current limitations, with future improvements anticipated through PEP-725. It allows for customization of binary package dependencies and build configurations. ```nix { # overrides-wheels.nix # This file is intended to be included by another Nix file. # It defines overrides for wheel builds. # Example structure (actual content may vary based on the include): # { # pkgs ? import {}, # uv2nix ? (pkgs.callPackage ./default.nix {}) # }: # # uv2nix.overrideAttrs (oldAttrs: { # # Add or modify build inputs, phases, or other attributes here # # For wheels, this might involve specifying different CFLAGS or LDFLAGS # # or ensuring specific system libraries are available. # buildInputs = oldAttrs.buildInputs ++ [ pkgs.anotherDependency ]; # }) } ``` -------------------------------- ### Override MacOS SDK version in stdenv Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/platform-quirks.md Demonstrates how to override the darwinSdkVersion within the stdenv.targetPlatform configuration. This is necessary when the default Nixpkgs SDK version does not match the intended target MacOS version. ```nix pkgs.callPackage pyproject-nix.build.packages { inherit python; stdenv = pkgs.stdenv.override { targetPlatform = pkgs.stdenv.targetPlatform // { # Sets MacOS SDK version to 15.1 which implies Darwin version 24. # See https://en.wikipedia.org/wiki/MacOS_version_history#Releases for more background on version numbers. darwinSdkVersion = "15.1"; }; }; }; ``` -------------------------------- ### Configure Nix Flake for Testing Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/testing.md Defines the flake.nix structure to include test derivations and expose them via the checks output. This allows for automated testing of Python packages within the Nix ecosystem. ```nix {{#include ./testing/flake.nix}} ``` -------------------------------- ### Load PEP-723 Inline Metadata Scripts Source: https://context7.com/pyproject-nix/uv2nix/llms.txt The `loadScript` function in uv2nix processes Python scripts containing inline metadata according to PEP-723. It parses the script's dependencies and Python version requirements to generate Nix overlays and virtual environments, enabling these scripts to be built and executed within a Nix environment. The function can also utilize a lock file for deterministic dependency resolution. ```python # scripts/example.py # /// script # requires-python = ">=3.12" # dependencies = [ # "tqdm", # "requests", # ] # /// # from tqdm import tqdm # import requests # ... ``` ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; # Load a PEP-723 script with its lock file script = uv2nix.lib.scripts.loadScript { script = ./scripts/example.py; # Lock file defaults to ./scripts/example.py.lock lockPath = ./scripts/example.py.lock; # Optional: Override inferred configuration config = { }; }; pythonBase = pkgs.callPackage pyproject-nix.build.packages { python = pkgs.python312; }; # Create overlay from script dependencies scriptOverlay = script.mkOverlay { sourcePreference = "wheel"; }; pythonSet = pythonBase.overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.wheel scriptOverlay ] ); # Create virtual environment for the script venv = script.mkVirtualEnv { inherit pythonSet; }; # Create executable script with proper shebang executableScript = pkgs.writeScript script.name ( script.renderScript { inherit venv; } ); in { packages.x86_64-linux.example = executableScript; apps.x86_64-linux.example = { type = "app"; program = "${executableScript}"; }; }; } ``` -------------------------------- ### Configure private index in pyproject.toml Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/private-deps.md Defines a custom package index and source mapping within the project configuration file to enable fetching from private repositories. ```toml [project] name = "with-private-deps" version = "0.1.0" requires-python = ">=3.12" dependencies = ["iniconfig"] [[tool.uv.index]] name = "my-index" url = "https://pypi-proxy.fly.dev/basic-auth/simple" explicit = true [tool.uv.sources] iniconfig = { index = "my-index" } [build-system] requires = ["setuptools>=42"] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Define netrc credentials Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/private-deps.md Specifies the machine credentials required for authentication against the private package index. ```text machine pypi-proxy.fly.dev login public password heron ``` -------------------------------- ### Override Python Packages for Source (sdist) Builds in Nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt This snippet shows how to override Python packages for source distributions (sdist) in Nix. It adds necessary build dependencies like `zeromq`, build system tools (`cmake`, `ninja`, `packaging`, `scikit-build-core`, `cython`), and Rust toolchain (`rustc`, `cargo`) for packages like `pyzmq` and `cryptography` that are not specified in `uv.lock`. ```nix { outputs = { nixpkgs, pyproject-nix, uv2nix, pyproject-build-systems, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; workspace = uv2nix.lib.workspace.loadWorkspace { workspaceRoot = ./.; }; # Override for sdist builds pyprojectOverrides = final: prev: { pyzmq = prev.pyzmq.overrideAttrs (old: { # Add system library dependency buildInputs = (old.buildInputs or [ ]) ++ [ pkgs.zeromq ]; # Add build system dependencies not in uv.lock nativeBuildInputs = old.nativeBuildInputs ++ [ (final.resolveBuildSystem { cmake = [ ]; ninja = [ ]; packaging = [ ]; scikit-build-core = [ ]; cython = [ ]; }) ]; }); # Example: Package requiring Rust toolchain cryptography = prev.cryptography.overrideAttrs (old: { nativeBuildInputs = old.nativeBuildInputs ++ [ pkgs.rustc pkgs.cargo ]; }); }; pythonSet = (pkgs.callPackage pyproject-nix.build.packages { python = pkgs.python312; }).overrideScope ( pkgs.lib.composeManyExtensions [ pyproject-build-systems.overlays.sdist # Note: sdist overlay (workspace.mkPyprojectOverlay { sourcePreference = "sdist"; }) pyprojectOverrides ] ); in { packages.x86_64-linux.default = pythonSet.mkVirtualEnv "app-env" workspace.deps.default; }; } ``` -------------------------------- ### Parse and Analyze uv.lock File with Nix Source: https://context7.com/pyproject-nix/uv2nix/llms.txt This Nix code snippet demonstrates how to parse a uv.lock file using the uv2nix.lib.lock1.parseLock function. It shows how to access various parts of the parsed lock data, filter local packages, retrieve local project information, and resolve dependencies for a specific Python environment. The output is a JSON string of resolved package names. ```nix { outputs = { nixpkgs, uv2nix, pyproject-nix, ... }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; inherit (pkgs) lib; # Parse uv.lock file uvLock = uv2nix.lib.lock1.parseLock (lib.importTOML ./uv.lock); # Access parsed lock data # uvLock.version - Lock file version # uvLock.requires-python - Python version constraints # uvLock.package - List of all packages # uvLock.conflicts - Dependency conflicts # uvLock.manifest - Workspace manifest # Filter local packages localPackages = lib.filter uv2nix.lib.lock1.isLocalPackage uvLock.package; # Get local project information localProjects = uv2nix.lib.lock1.getLocalProjects { lock = uvLock; workspaceRoot = ./.; inherit localPackages; }; # Resolve dependencies for a specific environment environ = pyproject-nix.lib.pep508.mkEnviron pkgs.python312; resolved = uv2nix.lib.lock1.resolveDependencies { lock = uvLock; inherit environ; dependencies = [ "my-package" ]; }; in { # Output resolved packages for inspection debug = builtins.toJSON (lib.attrNames resolved); }; } ``` -------------------------------- ### Nix Overlay for uv2nix with Older Nixpkgs Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/old-nixpkgs.md This Nix overlay ensures that a compatible version of 'uv' (>=0.5.7) is available when using uv2nix with older nixpkgs channels (<= 24.11). It overrides the default 'uv' package with the one provided by uv2nix. ```nix import nixpkgs { overlays = [ (final: prev: { uv = inputs.uv2nix.packages.${system}.uv-bin; }) ]; } ``` -------------------------------- ### Configure Nix Flake for Development Scripts Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/patterns/scripts.md This Nix expression configures a flake to manage development scripts. It takes a directory of scripts, wraps them in a virtual environment, and makes them accessible via `nix run`. ```nix { description = "Development scripts"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; flake-utils.url = "github:numtide/flake-utils"; }; outputs = { self, nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system: { packages = { # Example: wrap scripts in a virtualenv dev-scripts = nixpkgs.python3Packages.buildPythonApplication { pname = "dev-scripts"; version = "0.1.0"; src = ./.; # Example: scripts in examples/ # You can also use a specific directory like ./examples # pythonImports = [ ]; # No python imports needed for simple scripts # If your scripts need python packages, list them here # nativeBuildInputs = [ nixpkgs.python3Packages.poetry ]; # buildInputs = [ nixpkgs.python3Packages.requests ]; # Ensure scripts are executable postInstall = '' # Make sure scripts in examples/ are executable chmod +x examples/* ''; }; }; # Make scripts runnable with `nix run` apps.dev-scripts = { type = "app"; program = "${self.packages.${system}.dev-scripts}/bin/run-dev-scripts"; }; }); } ``` -------------------------------- ### Override sdist Builds with Nix Source: https://github.com/pyproject-nix/uv2nix/blob/master/doc/src/overriding/index.md This Nix code snippet demonstrates how to override source distribution (sdist) builds. It's a temporary solution until uv supports locking build systems. This approach is useful for managing build system dependencies during the packaging process. ```nix { # overrides-sdist.nix # This file is intended to be included by another Nix file. # It defines overrides for sdist builds. # Example structure (actual content may vary based on the include): # { # pkgs ? import {}, # uv2nix ? (pkgs.callPackage ./default.nix {}) # }: # # uv2nix.overrideAttrs (oldAttrs: { # # Add or modify build inputs, phases, or other attributes here # buildInputs = oldAttrs.buildInputs ++ [ pkgs.someDependency ]; # }) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.