Packaging/Python: Difference between revisions
m Category:Python added |
Add a section to explain how to locally test a packaged Python library |
||
| Line 15: | Line 15: | ||
You can now run <code>nix-shell</code> and it will drop you in a shell similar to the <code>python setup.py develop</code> mode which uses the local code in <tt>./path/to/source</tt> as input. <code>propagatedBuildInputs</code> will contain the packages you need in your project. | You can now run <code>nix-shell</code> and it will drop you in a shell similar to the <code>python setup.py develop</code> mode which uses the local code in <tt>./path/to/source</tt> as input. <code>propagatedBuildInputs</code> will contain the packages you need in your project. | ||
After you've finished developing you can replace the relative path with <code>fetchFromGitHub { ... }</code> or <code>[https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/fetchpypi/default.nix fetchPypi] { ... }</code>. | After you've finished developing you can replace the relative path with <code>fetchFromGitHub { ... }</code> or <code>[https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/fetchpypi/default.nix fetchPypi] { ... }</code>. | ||
== Testing out a module in a Python shell == | |||
Once you have your derivation written, you can create a [[Flakes|flake]] to give yourself a shell and easily test out the module you wrote the derivation for. | |||
Create a <code>flake.nix</code> next to your derivation:<syntaxhighlight lang="nix"> | |||
{ | |||
description = "Dev shell using external derivation"; | |||
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: | |||
let | |||
pkgs = import nixpkgs { inherit system; }; | |||
python = pkgs.python3; | |||
# replace ./default.nix with the path to your derivation, relative to this file | |||
mypackage = pkgs.callPackage ./default.nix { | |||
inherit (python.pkgs) buildPythonPackage package names of dependencies here; | |||
lib = pkgs.lib; | |||
}; | |||
in { | |||
devShells.default = pkgs.mkShell { | |||
buildInputs = [ python mypackage ]; | |||
}; | |||
}); | |||
} | |||
</syntaxhighlight>Replace "mypackage" with your package name, and "package names of dependencies here" with a (space-separated) list of the dependencies you listed in your buildPythonPackage call. | |||
Next, enter the devShell and launch a Python REPL:<syntaxhighlight lang="shell-session"> | |||
$ nix develop | |||
$ python | |||
Python 3.11.10 (main, Sep 7 2024, 01:03:31) [GCC 13.2.0] on linux | |||
Type "help", "copyright", "credits" or "license" for more information. | |||
>>> import mypackage | |||
>>> # test things out... | |||
</syntaxhighlight> | |||
== Pip and Virtualenv enabled nix-shell == | == Pip and Virtualenv enabled nix-shell == | ||