3 ## Reference {#reference}
5 ### Interpreters {#interpreters}
7 @python-interpreter-table@
9 The Nix expressions for the interpreters can be found in
10 `pkgs/development/interpreters/python`.
12 All packages depending on any Python interpreter get appended
13 `out/{python.sitePackages}` to `$PYTHONPATH` if such directory
16 #### Missing `tkinter` module standard library {#missing-tkinter-module-standard-library}
18 To reduce closure size the `Tkinter`/`tkinter` is available as a separate package, `pythonPackages.tkinter`.
20 #### Attributes on interpreters packages {#attributes-on-interpreters-packages}
22 Each interpreter has the following attributes:
24 - `libPrefix`. Name of the folder in `${python}/lib/` for corresponding interpreter.
25 - `interpreter`. Alias for `${python}/bin/${executable}`.
26 - `buildEnv`. Function to build python interpreter environments with extra packages bundled together. See [](#python.buildenv-function) for usage and documentation.
27 - `withPackages`. Simpler interface to `buildEnv`. See [](#python.withpackages-function) for usage and documentation.
28 - `sitePackages`. Alias for `lib/${libPrefix}/site-packages`.
29 - `executable`. Name of the interpreter executable, e.g. `python3.10`.
30 - `pkgs`. Set of Python packages for that specific interpreter. The package set can be modified by overriding the interpreter and passing `packageOverrides`.
32 ### Building packages and applications {#building-packages-and-applications}
34 Python libraries and applications that use tools to follow PEP 517 (e.g. `setuptools` or `hatchling`, etc.) or
35 previous tools such as `distutils` are typically built with respectively the [`buildPythonPackage`](#buildpythonpackage-function) and
36 [`buildPythonApplication`](#buildpythonapplication-function) functions. These two functions also support installing a `wheel`.
38 All Python packages reside in `pkgs/top-level/python-packages.nix` and all
39 applications elsewhere. In case a package is used as both a library and an
40 application, then the package should be in `pkgs/top-level/python-packages.nix`
41 since only those packages are made available for all interpreter versions. The
42 preferred location for library expressions is in
43 `pkgs/development/python-modules`. It is important that these packages are
44 called from `pkgs/top-level/python-packages.nix` and not elsewhere, to guarantee
45 the right version of the package is built.
47 Based on the packages defined in `pkgs/top-level/python-packages.nix` an
48 attribute set is created for each available Python interpreter. The available
51 * `pkgs.python27Packages`
52 * `pkgs.python3Packages`
53 * `pkgs.python39Packages`
54 * `pkgs.python310Packages`
55 * `pkgs.python311Packages`
56 * `pkgs.python312Packages`
57 * `pkgs.python313Packages`
58 * `pkgs.python314Packages`
59 * `pkgs.pypy27Packages`
60 * `pkgs.pypy39Packages`
61 * `pkgs.pypy310Packages`
65 * `pkgs.python2Packages` pointing to `pkgs.python27Packages`
66 * `pkgs.python3Packages` pointing to `pkgs.python312Packages`
67 * `pkgs.pythonPackages` pointing to `pkgs.python2Packages`
68 * `pkgs.pypy2Packages` pointing to `pkgs.pypy27Packages`
69 * `pkgs.pypy3Packages` pointing to `pkgs.pypy39Packages`
70 * `pkgs.pypyPackages` pointing to `pkgs.pypy2Packages`
73 #### `buildPythonPackage` function {#buildpythonpackage-function}
75 The `buildPythonPackage` function has its name binding in
76 `pkgs/development/interpreters/python/python-packages-base.nix` and is
77 implemented in `pkgs/development/interpreters/python/mk-python-derivation.nix`
80 The following is an example:
102 buildPythonPackage rec {
108 inherit pname version;
109 hash = "sha256-z4Q23FnYaVNG/NOrKW3kZCXsqwDWQJbOvnn7Ueyy65M=";
113 # don't test bash builtins
114 rm testing/test_argcomplete.py
130 nativeCheckInputs = [
135 changelog = "https://github.com/pytest-dev/pytest/releases/tag/${version}";
136 description = "Framework for writing tests";
137 homepage = "https://github.com/pytest-dev/pytest";
138 license = lib.licenses.mit;
139 maintainers = with lib.maintainers; [ domenkozar lovek323 madjar lsix ];
144 The `buildPythonPackage` mainly does four things:
146 * In the [`buildPhase`](#build-phase), it calls `${python.pythonOnBuildForHost.interpreter} -m build --wheel` to
147 build a wheel binary zipfile.
148 * In the [`installPhase`](#ssec-install-phase), it installs the wheel file using `${python.pythonOnBuildForHost.interpreter} -m installer *.whl`.
149 * In the [`postFixup`](#var-stdenv-postFixup) phase, the `wrapPythonPrograms` bash function is called to
150 wrap all programs in the `$out/bin/*` directory to include `$PATH`
151 environment variable and add dependent libraries to script's `sys.path`.
152 * In the [`installCheck`](#ssec-installCheck-phase) phase, `${python.interpreter} -m pytest` is run.
154 By default tests are run because [`doCheck = true`](#var-stdenv-doCheck). Test dependencies, like
155 e.g. the test runner, should be added to [`nativeCheckInputs`](#var-stdenv-nativeCheckInputs).
157 By default `meta.platforms` is set to the same value
158 as the interpreter unless overridden otherwise.
160 ##### `buildPythonPackage` parameters {#buildpythonpackage-parameters}
162 All parameters from [`stdenv.mkDerivation`](#sec-using-stdenv) function are still supported. The
163 following are specific to `buildPythonPackage`:
165 * `catchConflicts ? true`: If `true`, abort package build if a package name
166 appears more than once in dependency tree. Default is `true`.
167 * `disabled ? false`: If `true`, package is not built for the particular Python
169 * `dontWrapPythonPrograms ? false`: Skip wrapping of Python programs.
170 * `permitUserSite ? false`: Skip setting the `PYTHONNOUSERSITE` environment
171 variable in wrapped programs.
172 * `pyproject`: Whether the pyproject format should be used. As all other formats
173 are deprecated, you are recommended to set this to `true`. When you do so,
174 `pypaBuildHook` will be used, and you can add the required build dependencies
175 from `build-system.requires` to `build-system`. Note that the pyproject
176 format falls back to using `setuptools`, so you can use `pyproject = true`
177 even if the package only has a `setup.py`. When set to `false`, you can
178 use the existing [hooks](#setup-hooks) or provide your own logic to build the
179 package. This can be useful for packages that don't support the pyproject
180 format. When unset, the legacy `setuptools` hooks are used for backwards
182 * `makeWrapperArgs ? []`: A list of strings. Arguments to be passed to
183 [`makeWrapper`](#fun-makeWrapper), which wraps generated binaries. By default, the arguments to
184 [`makeWrapper`](#fun-makeWrapper) set `PATH` and `PYTHONPATH` environment variables before calling
185 the binary. Additional arguments here can allow a developer to set environment
186 variables which will be available when the binary is run. For example,
187 `makeWrapperArgs = ["--set FOO BAR" "--set BAZ QUX"]`.
188 * `namePrefix`: Prepends text to `${name}` parameter. In case of libraries, this
189 defaults to `"python3.8-"` for Python 3.8, etc., and in case of applications to `""`.
190 * `pypaBuildFlags ? []`: A list of strings. Arguments to be passed to `python -m build --wheel`.
191 * `pythonPath ? []`: List of packages to be added into `$PYTHONPATH`. Packages
192 in `pythonPath` are not propagated (contrary to [`propagatedBuildInputs`](#var-stdenv-propagatedBuildInputs)).
193 * `preShellHook`: Hook to execute commands before `shellHook`.
194 * `postShellHook`: Hook to execute commands after `shellHook`.
195 * `removeBinByteCode ? true`: Remove bytecode from `/bin`. Bytecode is only
196 created when the filenames end with `.py`.
197 * `setupPyGlobalFlags ? []`: List of flags passed to `setup.py` command.
198 * `setupPyBuildFlags ? []`: List of flags passed to `setup.py build_ext` command.
200 The [`stdenv.mkDerivation`](#sec-using-stdenv) function accepts various parameters for describing
201 build inputs (see "Specifying dependencies"). The following are of special
202 interest for Python packages, either because these are primarily used, or
203 because their behaviour is different:
205 * `nativeBuildInputs ? []`: Build-time only dependencies. Typically executables.
206 * `build-system ? []`: Build-time only Python dependencies. Items listed in `build-system.requires`/`setup_requires`.
207 * `buildInputs ? []`: Build and/or run-time dependencies that need to be
208 compiled for the host machine. Typically non-Python libraries which are being
210 * `nativeCheckInputs ? []`: Dependencies needed for running the [`checkPhase`](#ssec-check-phase). These
211 are added to [`nativeBuildInputs`](#var-stdenv-nativeBuildInputs) when [`doCheck = true`](#var-stdenv-doCheck). Items listed in
212 `tests_require` go here.
213 * `dependencies ? []`: Aside from propagating dependencies,
214 `buildPythonPackage` also injects code into and wraps executables with the
215 paths included in this list. Items listed in `install_requires` go here.
216 * `optional-dependencies ? { }`: Optional feature flagged dependencies. Items listed in `extras_requires` go here.
219 ##### Overriding Python packages {#overriding-python-packages}
221 The `buildPythonPackage` function has a `overridePythonAttrs` method that can be
222 used to override the package. In the following example we create an environment
223 where we have the `blaze` package using an older version of `pandas`. We
224 override first the Python interpreter and pass `packageOverrides` which contains
225 the overrides for packages in the package set.
228 with import <nixpkgs> {};
232 packageOverrides = self: super: {
233 pandas = super.pandas.overridePythonAttrs(old: rec {
238 hash = "sha256-JQn+rtpy/OA2deLszSKEuxyttqBzcAil50H+JDHUdCE=";
242 in pkgs.python3.override {inherit packageOverrides; self = python;};
244 in python.withPackages(ps: [ ps.blaze ])).env
247 The next example shows a non trivial overriding of the `blas` implementation to
248 be used through out all of the Python package set:
252 python3MyBlas = pkgs.python3.override {
253 packageOverrides = self: super: {
254 # We need toPythonModule for the package set to evaluate this
255 blas = super.toPythonModule(super.pkgs.blas.override {
256 blasProvider = super.pkgs.mkl;
258 lapack = super.toPythonModule(super.pkgs.lapack.override {
259 lapackProvider = super.pkgs.mkl;
266 This is particularly useful for numpy and scipy users who want to gain speed with other blas implementations.
267 Note that using `scipy = super.scipy.override { blas = super.pkgs.mkl; };` will likely result in
268 compilation issues, because scipy dependencies need to use the same blas implementation as well.
270 #### `buildPythonApplication` function {#buildpythonapplication-function}
272 The [`buildPythonApplication`](#buildpythonapplication-function) function is practically the same as
273 [`buildPythonPackage`](#buildpythonpackage-function). The main purpose of this function is to build a Python
274 package where one is interested only in the executables, and not importable
275 modules. For that reason, when adding this package to a [`python.buildEnv`](#python.buildenv-function), the
276 modules won't be made available.
278 Another difference is that [`buildPythonPackage`](#buildpythonpackage-function) by default prefixes the names of
279 the packages with the version of the interpreter. Because this is irrelevant for
280 applications, the prefix is omitted.
282 When packaging a Python application with [`buildPythonApplication`](#buildpythonapplication-function), it should be
283 called with `callPackage` and passed `python3` or `python3Packages` (possibly
284 specifying an interpreter version), like this:
292 python3Packages.buildPythonApplication rec {
298 inherit pname version;
299 hash = "sha256-Pe229rT0aHwA98s+nTHQMEFKZPo/yw6sot8MivFDvAw=";
302 build-system = with python3Packages; [
306 dependencies = with python3Packages; [
317 This is then added to `pkgs/by-name` just as any other application would be.
319 Since the package is an application, a consumer doesn't need to care about
320 Python versions or modules, which is why they don't go in `python3Packages`.
322 #### `toPythonApplication` function {#topythonapplication-function}
324 A distinction is made between applications and libraries, however, sometimes a
325 package is used as both. In this case the package is added as a library to
326 `python-packages.nix` and as an application to `pkgs/by-name`. To reduce
327 duplication the `toPythonApplication` can be used to convert a library to an
330 The Nix expression shall use [`buildPythonPackage`](#buildpythonpackage-function) and be called from
331 `python-packages.nix`. A reference shall be created from `pkgs/by-name` to
332 the attribute in `python-packages.nix`, and the `toPythonApplication` shall be
333 applied to the reference:
340 python3Packages.toPythonApplication python3Packages.youtube-dl
343 #### `toPythonModule` function {#topythonmodule-function}
345 In some cases, such as bindings, a package is created using
346 [`stdenv.mkDerivation`](#sec-using-stdenv) and added as attribute in `pkgs/by-name` or in `all-packages.nix`. The Python
347 bindings should be made available from `python-packages.nix`. The
348 `toPythonModule` function takes a derivation and makes certain Python-specific
353 opencv = toPythonModule (pkgs.opencv.override {
355 pythonPackages = self;
360 Do pay attention to passing in the right Python version!
362 #### `mkPythonMetaPackage` function {#mkpythonmetapackage-function}
364 This will create a meta package containing [metadata files](https://packaging.python.org/en/latest/specifications/recording-installed-packages/) to satisfy a dependency on a package, without it actually having been installed into the environment.
365 In nixpkgs this is used to package Python packages with split binary/source distributions such as [psycopg2](https://pypi.org/project/psycopg2/)/[psycopg2-binary](https://pypi.org/project/psycopg2-binary/).
368 mkPythonMetaPackage {
369 pname = "psycopg2-binary";
370 inherit (psycopg2) optional-dependencies version;
371 dependencies = [ psycopg2 ];
373 inherit (psycopg2.meta) description homepage;
378 #### `mkPythonEditablePackage` function {#mkpythoneditablepackage-function}
380 When developing Python packages it's common to install packages in [editable mode](https://setuptools.pypa.io/en/latest/userguide/development_mode.html).
381 Like `mkPythonMetaPackage` this function exists to create an otherwise empty package, but also containing a pointer to an impure location outside the Nix store that can be changed without rebuilding.
383 The editable root is passed as a string. Normally `.pth` files contains absolute paths to the mutable location. This isn't always ergonomic with Nix, so environment variables are expanded at runtime.
384 This means that a shell hook setting up something like a `$REPO_ROOT` variable can be used as the relative package root.
386 As an implementation detail, the [PEP-518](https://peps.python.org/pep-0518/) `build-system` specified won't be used, but instead the editable package will be built using [hatchling](https://pypi.org/project/hatchling/).
387 The `build-system`'s provided will instead become runtime dependencies of the editable package.
389 Note that overriding packages deeper in the dependency graph _can_ work, but it's not the primary use case and overriding existing packages can make others break in unexpected ways.
392 { pkgs ? import <nixpkgs> { } }:
395 pyproject = pkgs.lib.importTOML ./pyproject.toml;
397 myPython = pkgs.python.override {
399 packageOverrides = pyfinal: pyprev: {
400 # An editable package with a script that loads our mutable location
401 my-editable = pyfinal.mkPythonEditablePackage {
402 # Inherit project metadata from pyproject.toml
403 pname = pyproject.project.name;
404 inherit (pyproject.project) version;
406 # The editable root passed as a string
407 root = "$REPO_ROOT/src"; # Use environment variable expansion at runtime
409 # Inject a script (other PEP-621 entrypoints are also accepted)
410 inherit (pyproject.project) scripts;
415 pythonEnv = myPython.withPackages (ps: [ ps.my-editable ]);
418 packages = [ pythonEnv ];
422 #### `python.buildEnv` function {#python.buildenv-function}
424 Python environments can be created using the low-level `pkgs.buildEnv` function.
425 This example shows how to create an environment that has the Pyramid Web Framework.
426 Saving the following as `default.nix`
429 with import <nixpkgs> {};
431 python3.buildEnv.override {
432 extraLibs = [ python3Packages.pyramid ];
433 ignoreCollisions = true;
437 and running `nix-build` will create
440 /nix/store/cf1xhjwzmdki7fasgr4kz6di72ykicl5-python-2.7.8-env
443 with wrapped binaries in `bin/`.
445 You can also use the `env` attribute to create local environments with needed
446 packages installed. This is somewhat comparable to `virtualenv`. For example,
447 running `nix-shell` with the following `shell.nix`
450 with import <nixpkgs> {};
452 (python3.buildEnv.override {
453 extraLibs = with python3Packages; [
460 will drop you into a shell where Python will have the
461 specified packages in its path.
463 ##### `python.buildEnv` arguments {#python.buildenv-arguments}
466 * `extraLibs`: List of packages installed inside the environment.
467 * `postBuild`: Shell command executed after the build of environment.
468 * `ignoreCollisions`: Ignore file collisions inside the environment (default is `false`).
469 * `permitUserSite`: Skip setting the `PYTHONNOUSERSITE` environment variable in
470 wrapped binaries in the environment.
472 #### `python.withPackages` function {#python.withpackages-function}
474 The [`python.withPackages`](#python.withpackages-function) function provides a simpler interface to the [`python.buildEnv`](#python.buildenv-function) functionality.
475 It takes a function as an argument that is passed the set of python packages and returns the list
476 of the packages to be included in the environment. Using the [`withPackages`](#python.withpackages-function) function, the previous
477 example for the Pyramid Web Framework environment can be written like this:
480 with import <nixpkgs> {};
482 python.withPackages (ps: [ ps.pyramid ])
485 [`withPackages`](#python.withpackages-function) passes the correct package set for the specific interpreter
486 version as an argument to the function. In the above example, `ps` equals
487 `pythonPackages`. But you can also easily switch to using python3:
490 with import <nixpkgs> {};
492 python3.withPackages (ps: [ ps.pyramid ])
495 Now, `ps` is set to `python3Packages`, matching the version of the interpreter.
497 As [`python.withPackages`](#python.withpackages-function) uses [`python.buildEnv`](#python.buildenv-function) under the hood, it also
498 supports the `env` attribute. The `shell.nix` file from the previous section can
499 thus be also written like this:
502 with import <nixpkgs> {};
504 (python3.withPackages (ps: with ps; [
510 In contrast to [`python.buildEnv`](#python.buildenv-function), [`python.withPackages`](#python.withpackages-function) does not support the
511 more advanced options such as `ignoreCollisions = true` or `postBuild`. If you
512 need them, you have to use [`python.buildEnv`](#python.buildenv-function).
514 Python 2 namespace packages may provide `__init__.py` that collide. In that case
515 [`python.buildEnv`](#python.buildenv-function) should be used with `ignoreCollisions = true`.
517 #### Setup hooks {#setup-hooks}
519 The following are setup hooks specifically for Python packages. Most of these
520 are used in [`buildPythonPackage`](#buildpythonpackage-function).
522 - `eggUnpackhook` to move an egg to the correct folder so it can be installed
523 with the `eggInstallHook`
524 - `eggBuildHook` to skip building for eggs.
525 - `eggInstallHook` to install eggs.
526 - `pypaBuildHook` to build a wheel using
527 [`pypa/build`](https://pypa-build.readthedocs.io/en/latest/index.html) and
528 PEP 517/518. Note a build system (e.g. `setuptools` or `flit`) should still
529 be added as `build-system`.
530 - `pypaInstallHook` to install wheels.
531 - `pytestCheckHook` to run tests with `pytest`. See [example usage](#using-pytestcheckhook).
532 - `pythonCatchConflictsHook` to fail if the package depends on two different versions of the same dependency.
533 - `pythonImportsCheckHook` to check whether importing the listed modules works.
534 - `pythonRelaxDepsHook` will relax Python dependencies restrictions for the package.
535 See [example usage](#using-pythonrelaxdepshook).
536 - `pythonRemoveBinBytecode` to remove bytecode from the `/bin` folder.
537 - `setuptoolsBuildHook` to build a wheel using `setuptools`.
538 - `sphinxHook` to build documentation and manpages using Sphinx.
539 - `venvShellHook` to source a Python 3 `venv` at the `venvDir` location. A
540 `venv` is created if it does not yet exist. `postVenvCreation` can be used to
541 to run commands only after venv is first created.
542 - `wheelUnpackHook` to move a wheel to the correct folder so it can be installed
543 with the `pipInstallHook`.
544 - `unittestCheckHook` will run tests with `python -m unittest discover`. See [example usage](#using-unittestcheckhook).
546 ## User Guide {#user-guide}
548 ### Using Python {#using-python}
550 #### Overview {#overview}
552 Several versions of the Python interpreter are available on Nix, as well as a
553 high amount of packages. The attribute `python3` refers to the default
554 interpreter, which is currently CPython 3.11. The attribute `python` refers to
555 CPython 2.7 for backwards-compatibility. It is also possible to refer to
556 specific versions, e.g. `python311` refers to CPython 3.11, and `pypy` refers to
557 the default PyPy interpreter.
559 Python is used a lot, and in different ways. This affects also how it is
560 packaged. In the case of Python on Nix, an important distinction is made between
561 whether the package is considered primarily an application, or whether it should
562 be used as a library, i.e., of primary interest are the modules in
563 `site-packages` that should be importable.
565 In the Nixpkgs tree Python applications can be found throughout, depending on
566 what they do, and are called from the main package set. Python libraries,
567 however, are in separate sets, with one set per interpreter version.
569 The interpreters have several common attributes. One of these attributes is
570 `pkgs`, which is a package set of Python libraries for this specific
571 interpreter. E.g., the `toolz` package corresponding to the default interpreter
572 is `python3.pkgs.toolz`, and the CPython 3.11 version is `python311.pkgs.toolz`.
573 The main package set contains aliases to these package sets, e.g.
574 `pythonPackages` refers to `python.pkgs` and `python311Packages` to
577 #### Installing Python and packages {#installing-python-and-packages}
579 The Nix and NixOS manuals explain how packages are generally installed. In the
580 case of Python and Nix, it is important to make a distinction between whether the
581 package is considered an application or a library.
583 Applications on Nix are typically installed into your user profile imperatively
584 using `nix-env -i`, and on NixOS declaratively by adding the package name to
585 `environment.systemPackages` in `/etc/nixos/configuration.nix`. Dependencies
586 such as libraries are automatically installed and should not be installed
589 The same goes for Python applications. Python applications can be installed in
590 your profile, and will be wrapped to find their exact library dependencies,
591 without impacting other applications or polluting your user environment.
593 But Python libraries you would like to use for development cannot be installed,
594 at least not individually, because they won't be able to find each other
595 resulting in import errors. Instead, it is possible to create an environment
596 with [`python.buildEnv`](#python.buildenv-function) or [`python.withPackages`](#python.withpackages-function) where the interpreter and other
597 executables are wrapped to be able to find each other and all of the modules.
599 In the following examples we will start by creating a simple, ad-hoc environment
600 with a nix-shell that has `numpy` and `toolz` in Python 3.11; then we will create
601 a re-usable environment in a single-file Python script; then we will create a
602 full Python environment for development with this same environment.
604 Philosophically, this should be familiar to users who are used to a `venv` style
605 of development: individual projects create their own Python environments without
606 impacting the global environment or each other.
608 #### Ad-hoc temporary Python environment with `nix-shell` {#ad-hoc-temporary-python-environment-with-nix-shell}
610 The simplest way to start playing with the way nix wraps and sets up Python
611 environments is with `nix-shell` at the cmdline. These environments create a
612 temporary shell session with a Python and a *precise* list of packages (plus
613 their runtime dependencies), with no other Python packages in the Python
616 To create a Python 3.11 session with `numpy` and `toolz` available, run:
619 $ nix-shell -p 'python311.withPackages(ps: with ps; [ numpy toolz ])'
622 By default `nix-shell` will start a `bash` session with this interpreter in our
623 `PATH`, so if we then run:
626 [nix-shell:~/src/nixpkgs]$ python3
627 Python 3.11.3 (main, Apr 4 2023, 22:36:41) [GCC 12.2.0] on linux
628 Type "help", "copyright", "credits" or "license" for more information.
629 >>> import numpy; import toolz
632 Note that no other modules are in scope, even if they were imperatively
633 installed into our user environment as a dependency of a Python application:
637 Traceback (most recent call last):
638 File "<stdin>", line 1, in <module>
639 ModuleNotFoundError: No module named 'requests'
642 We can add as many additional modules onto the `nix-shell` as we need, and we
643 will still get 1 wrapped Python interpreter. We can start the interpreter
647 $ nix-shell -p "python311.withPackages (ps: with ps; [ numpy toolz requests ])" --run python3
648 this derivation will be built:
649 /nix/store/r19yf5qgfiakqlhkgjahbg3zg79549n4-python3-3.11.2-env.drv
650 building '/nix/store/r19yf5qgfiakqlhkgjahbg3zg79549n4-python3-3.11.2-env.drv'...
651 created 273 symlinks in user environment
652 Python 3.11.2 (main, Feb 7 2023, 13:52:42) [GCC 12.2.0] on linux
653 Type "help", "copyright", "credits" or "license" for more information.
658 Notice that this time it built a new Python environment, which now includes
659 `requests`. Building an environment just creates wrapper scripts that expose the
660 selected dependencies to the interpreter while re-using the actual modules. This
661 means if any other env has installed `requests` or `numpy` in a different
662 context, we don't need to recompile them -- we just recompile the wrapper script
663 that sets up an interpreter pointing to them. This matters much more for "big"
664 modules like `pytorch` or `tensorflow`.
666 Module names usually match their names on [pypi.org](https://pypi.org/), but
667 normalized according to PEP 503/508. (e.g. Foo__Bar.baz -> foo-bar-baz)
668 You can use the [Nixpkgs search website](https://nixos.org/nixos/packages.html)
669 to find them as well (along with non-python packages).
671 At this point we can create throwaway experimental Python environments with
672 arbitrary dependencies. This is a good way to get a feel for how the Python
673 interpreter and dependencies work in Nix and NixOS, but to do some actual
674 development, we'll want to make it a bit more persistent.
676 ##### Running Python scripts and using `nix-shell` as shebang {#running-python-scripts-and-using-nix-shell-as-shebang}
678 Sometimes, we have a script whose header looks like this:
681 #!/usr/bin/env python3
685 print(f"The dot product of {a} and {b} is: {np.dot(a, b)}")
688 Executing this script requires a `python3` that has `numpy`. Using what we learned
689 in the previous section, we could startup a shell and just run it like so:
692 $ nix-shell -p 'python311.withPackages (ps: with ps; [ numpy ])' --run 'python3 foo.py'
693 The dot product of [1 2] and [3 4] is: 11
696 But if we maintain the script ourselves, and if there are more dependencies, it
697 may be nice to encode those dependencies in source to make the script re-usable
698 without that bit of knowledge. That can be done by using `nix-shell` as a
699 [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)), like so:
702 #!/usr/bin/env nix-shell
703 #!nix-shell -i python3 -p "python3.withPackages(ps: [ ps.numpy ])"
707 print(f"The dot product of {a} and {b} is: {np.dot(a, b)}")
710 Then we execute it, without requiring any environment setup at all!
714 The dot product of [1 2] and [3 4] is: 11
717 If the dependencies are not available on the host where `foo.py` is executed, it
718 will build or download them from a Nix binary cache prior to starting up, prior
719 that it is executed on a machine with a multi-user nix installation.
721 This provides a way to ship a self bootstrapping Python script, akin to a
722 statically linked binary, where it can be run on any machine (provided nix is
723 installed) without having to assume that `numpy` is installed globally on the
726 By default it is pulling the import checkout of Nixpkgs itself from our nix
727 channel, which is nice as it cache aligns with our other package builds, but we
728 can make it fully reproducible by pinning the `nixpkgs` import:
731 #!/usr/bin/env nix-shell
732 #!nix-shell -i python3 -p "python3.withPackages (ps: [ ps.numpy ])"
733 #!nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/e51209796c4262bfb8908e3d6d72302fe4e96f5f.tar.gz
737 print(f"The dot product of {a} and {b} is: {np.dot(a, b)}")
740 This will execute with the exact same versions of Python 3.10, numpy, and system
741 dependencies a year from now as it does today, because it will always use
742 exactly git commit `e51209796c4262bfb8908e3d6d72302fe4e96f5f` of Nixpkgs for all
743 of the package versions.
745 This is also a great way to ensure the script executes identically on different
748 ##### Load environment from `.nix` expression {#load-environment-from-.nix-expression}
750 We've now seen how to create an ad-hoc temporary shell session, and how to
751 create a single script with Python dependencies, but in the course of normal
752 development we're usually working in an entire package repository.
754 As explained [in the `nix-shell` section](https://nixos.org/manual/nix/stable/command-ref/nix-shell) of the Nix manual, `nix-shell` can also load an expression from a `.nix` file.
755 Say we want to have Python 3.11, `numpy` and `toolz`, like before,
756 in an environment. We can add a `shell.nix` file describing our dependencies:
759 with import <nixpkgs> {};
760 (python311.withPackages (ps: with ps; [
766 And then at the command line, just typing `nix-shell` produces the same
767 environment as before. In a normal project, we'll likely have many more
768 dependencies; this can provide a way for developers to share the environments
769 with each other and with CI builders.
771 What's happening here?
773 1. We begin with importing the Nix Packages collections. `import <nixpkgs>`
774 imports the `<nixpkgs>` function, `{}` calls it and the `with` statement
775 brings all attributes of `nixpkgs` in the local scope. These attributes form
776 the main package set.
777 2. Then we create a Python 3.11 environment with the [`withPackages`](#python.withpackages-function) function, as before.
778 3. The [`withPackages`](#python.withpackages-function) function expects us to provide a function as an argument
779 that takes the set of all Python packages and returns a list of packages to
780 include in the environment. Here, we select the packages `numpy` and `toolz`
781 from the package set.
783 To combine this with `mkShell` you can:
786 with import <nixpkgs> {};
788 pythonEnv = python311.withPackages (ps: [
805 This will create a unified environment that has not just our Python interpreter
806 and its Python dependencies, but also tools like `black` or `mypy` and libraries
807 like `libffi` the `openssl` in scope. This is generic and can span any number of
808 tools or languages across the Nixpkgs ecosystem.
810 ##### Installing environments globally on the system {#installing-environments-globally-on-the-system}
812 Up to now, we've been creating environments scoped to an ad-hoc shell session,
813 or a single script, or a single project. This is generally advisable, as it
814 avoids pollution across contexts.
816 However, sometimes we know we will often want a Python with some basic packages,
817 and want this available without having to enter into a shell or build context.
818 This can be useful to have things like vim/emacs editors and plugins or shell
819 tools "just work" without having to set them up, or when running other software
820 that expects packages to be installed globally.
822 To create your own custom environment, create a file in `~/.config/nixpkgs/overlays/`
823 that looks like this:
826 # ~/.config/nixpkgs/overlays/myEnv.nix
828 myEnv = super.buildEnv {
831 # A Python 3 interpreter with some packages
832 (self.python3.withPackages (
840 # Some other packages we'd like as part of this env
850 You can then build and install this to your profile with:
856 One limitation of this is that you can only have 1 Python env installed
857 globally, since they conflict on the `python` to load out of your `PATH`.
859 If you get a conflict or prefer to keep the setup clean, you can have `nix-env`
860 atomically *uninstall* all other imperatively installed packages and replace
861 your profile with just `myEnv` by using the `--replace` flag.
863 ##### Environment defined in `/etc/nixos/configuration.nix` {#environment-defined-in-etcnixosconfiguration.nix}
865 For the sake of completeness, here's how to install the environment system-wide
871 environment.systemPackages = with pkgs; [
872 (python310.withPackages(ps: with ps; [ numpy toolz ]))
877 ### Developing with Python {#developing-with-python}
879 Above, we were mostly just focused on use cases and what to do to get started
880 creating working Python environments in nix.
882 Now that you know the basics to be up and running, it is time to take a step
883 back and take a deeper look at how Python packages are packaged on Nix.
885 #### Python library packages in Nixpkgs {#python-library-packages-in-nixpkgs}
887 With Nix all packages are built by functions. The main function in Nix for
888 building Python libraries is [`buildPythonPackage`](#buildpythonpackage-function). Let's see how we can build the
898 buildPythonPackage rec {
904 inherit pname version;
905 hash = "sha256-CP3V73yWSArRHBLUct4hrNMjWZlvaaUlkpm1QP66RWA=";
915 pythonImportsCheck = [
922 changelog = "https://github.com/pytoolz/toolz/releases/tag/${version}";
923 homepage = "https://github.com/pytoolz/toolz";
924 description = "List processing tools and functional utilities";
925 license = lib.licenses.bsd3;
930 What happens here? The function [`buildPythonPackage`](#buildpythonpackage-function) is called and as argument
931 it accepts a set. In this case the set is a recursive set, `rec`. One of the
932 arguments is the name of the package, which consists of a basename (generally
933 following the name on PyPI) and a version. Another argument, `src` specifies the
934 source, which in this case is fetched from PyPI using the helper function
935 `fetchPypi`. The argument `doCheck` is used to set whether tests should be run
936 when building the package. Since there are no tests, we rely on [`pythonImportsCheck`](#using-pythonimportscheck)
937 to test whether the package can be imported. Furthermore, we specify some meta
938 information. The output of the function is a derivation.
940 An expression for `toolz` can be found in the Nixpkgs repository. As explained
941 in the introduction of this Python section, a derivation of `toolz` is available
942 for each interpreter version, e.g. `python311.pkgs.toolz` refers to the `toolz`
943 derivation corresponding to the CPython 3.11 interpreter.
945 The above example works when you're directly working on
946 `pkgs/top-level/python-packages.nix` in the Nixpkgs repository. Often though,
947 you will want to test a Nix expression outside of the Nixpkgs tree.
949 The following expression creates a derivation for the `toolz` package,
950 and adds it along with a `numpy` package to a Python environment.
953 with import <nixpkgs> {};
956 my_toolz = python311.pkgs.buildPythonPackage rec {
962 inherit pname version;
963 hash = "sha256-CP3V73yWSArRHBLUct4hrNMjWZlvaaUlkpm1QP66RWA=";
967 python311.pkgs.setuptools
974 homepage = "https://github.com/pytoolz/toolz/";
975 description = "List processing tools and functional utilities";
980 in python311.withPackages (ps: with ps; [
987 Executing `nix-shell` will result in an environment in which you can use
988 Python 3.11 and the `toolz` package. As you can see we had to explicitly mention
989 for which Python version we want to build a package.
991 So, what did we do here? Well, we took the Nix expression that we used earlier
992 to build a Python environment, and said that we wanted to include our own
993 version of `toolz`, named `my_toolz`. To introduce our own package in the scope
994 of [`withPackages`](#python.withpackages-function) we used a `let` expression. You can see that we used
995 `ps.numpy` to select numpy from the nixpkgs package set (`ps`). We did not take
996 `toolz` from the Nixpkgs package set this time, but instead took our own version
997 that we introduced with the `let` expression.
999 #### Handling dependencies {#handling-dependencies}
1001 Our example, `toolz`, does not have any dependencies on other Python packages or system libraries.
1002 [`buildPythonPackage`](#buildpythonpackage-function) uses the the following arguments in the following circumstances:
1004 - `dependencies` - For Python runtime dependencies.
1005 - `build-system` - For Python build-time requirements.
1006 - [`buildInputs`](#var-stdenv-buildInputs) - For non-Python build-time requirements.
1007 - [`nativeCheckInputs`](#var-stdenv-nativeCheckInputs) - For test dependencies
1009 Dependencies can belong to multiple arguments, for example if something is both a build time requirement & a runtime dependency.
1011 The following example shows which arguments are given to [`buildPythonPackage`](#buildpythonpackage-function) in
1012 order to build [`datashape`](https://github.com/blaze/datashape).
1016 , buildPythonPackage
1019 # build dependencies
1023 , numpy, multipledispatch, python-dateutil
1029 buildPythonPackage rec {
1030 pname = "datashape";
1035 inherit pname version;
1036 hash = "sha256-FLLvdm1MllKrgTGC6Gb0k0deZeVYvtCCLji/B7uhong=";
1049 nativeCheckInputs = [
1054 changelog = "https://github.com/blaze/datashape/releases/tag/${version}";
1055 homepage = "https://github.com/ContinuumIO/datashape";
1056 description = "Data description language";
1057 license = lib.licenses.bsd2;
1062 We can see several runtime dependencies, `numpy`, `multipledispatch`, and
1063 `python-dateutil`. Furthermore, we have [`nativeCheckInputs`](#var-stdenv-nativeCheckInputs) with `pytestCheckHook`.
1064 `pytestCheckHook` is a test runner hook and is only used during the [`checkPhase`](#ssec-check-phase) and is
1065 therefore not added to `dependencies`.
1067 In the previous case we had only dependencies on other Python packages to consider.
1068 Occasionally you have also system libraries to consider. E.g., `lxml` provides
1069 Python bindings to `libxml2` and `libxslt`. These libraries are only required
1070 when building the bindings and are therefore added as [`buildInputs`](#var-stdenv-buildInputs).
1074 , buildPythonPackage
1081 buildPythonPackage rec {
1087 inherit pname version;
1088 hash = "sha256-s9NiusRxFydHzaNRMjjxFcvWxfi45jGb9ql6eJJyQJk=";
1100 # tests are meant to be ran "in-place" in the same directory as src
1103 pythonImportsCheck = [
1109 changelog = "https://github.com/lxml/lxml/releases/tag/lxml-${version}";
1110 description = "Pythonic binding for the libxml2 and libxslt libraries";
1111 homepage = "https://lxml.de";
1112 license = lib.licenses.bsd3;
1113 maintainers = with lib.maintainers; [ sjourdois ];
1118 In this example `lxml` and Nix are able to work out exactly where the relevant
1119 files of the dependencies are. This is not always the case.
1121 The example below shows bindings to The Fastest Fourier Transform in the West,
1122 commonly known as FFTW. On Nix we have separate packages of FFTW for the
1123 different types of floats (`"single"`, `"double"`, `"long-double"`). The
1124 bindings need all three types, and therefore we add all three as [`buildInputs`](#var-stdenv-buildInputs).
1125 The bindings don't expect to find each of them in a different folder, and
1126 therefore we have to set `LDFLAGS` and `CFLAGS`.
1130 , buildPythonPackage
1133 # build dependencies
1144 buildPythonPackage rec {
1150 inherit pname version;
1151 hash = "sha256-9ru2r6kwhUCaskiFoaPNuJCfCVoUL01J40byvRt4kHQ=";
1170 export LDFLAGS="-L${fftw.dev}/lib -L${fftwFloat.out}/lib -L${fftwLongDouble.out}/lib"
1171 export CFLAGS="-I${fftw.dev}/include -I${fftwFloat.dev}/include -I${fftwLongDouble.dev}/include"
1174 # Tests cannot import pyfftw. pyfftw works fine though.
1177 pythonImportsCheck = [ "pyfftw" ];
1180 changelog = "https://github.com/pyFFTW/pyFFTW/releases/tag/v${version}";
1181 description = "Pythonic wrapper around FFTW, the FFT library, presenting a unified interface for all the supported transforms";
1182 homepage = "http://hgomersall.github.com/pyFFTW";
1183 license = with lib.licenses; [ bsd2 bsd3 ];
1188 Note also the line [`doCheck = false;`](#var-stdenv-doCheck), we explicitly disabled running the test-suite.
1190 #### Testing Python Packages {#testing-python-packages}
1192 It is highly encouraged to have testing as part of the package build. This
1193 helps to avoid situations where the package was able to build and install,
1194 but is not usable at runtime.
1195 Your package should provide its own [`checkPhase`](#ssec-check-phase).
1198 The [`checkPhase`](#ssec-check-phase) for python maps to the `installCheckPhase` on a
1199 normal derivation. This is due to many python packages not behaving well
1200 to the pre-installed version of the package. Version info, and natively
1201 compiled extensions generally only exist in the install directory, and
1202 thus can cause issues when a test suite asserts on that behavior.
1206 Tests should only be disabled if they don't agree with nix
1207 (e.g. external dependencies, network access, flakey tests), however,
1208 as many tests should be enabled as possible. Failing tests can still be
1209 a good indication that the package is not in a valid state.
1212 #### Using pytest {#using-pytest}
1214 Pytest is the most common test runner for python repositories. A trivial
1219 nativeCheckInputs = [ pytest ];
1230 However, many repositories' test suites do not translate well to nix's build
1231 sandbox, and will generally need many tests to be disabled.
1233 To filter tests using pytest, one can do the following:
1237 nativeCheckInputs = [ pytest ];
1238 # avoid tests which need additional data or touch network
1242 pytest tests/ --ignore=tests/integration -k 'not download and not update' --ignore=tests/test_failing.py
1249 `--ignore` will tell pytest to ignore that file or directory from being
1250 collected as part of a test run. This is useful is a file uses a package
1251 which is not available in nixpkgs, thus skipping that test file is much
1252 easier than having to create a new package.
1254 `-k` is used to define a predicate for test names. In this example, we are
1255 filtering out tests which contain `download` or `update` in their test case name.
1256 Only one `-k` argument is allowed, and thus a long predicate should be concatenated
1257 with “\\” and wrapped to the next line.
1260 In pytest==6.0.1, the use of “\\” to continue a line (e.g. `-k 'not download \'`) has
1261 been removed, in this case, it's recommended to use `pytestCheckHook`.
1264 #### Using pytestCheckHook {#using-pytestcheckhook}
1266 `pytestCheckHook` is a convenient hook which will set up (or configure)
1267 a [`checkPhase`](#ssec-check-phase) to run `pytest`. This is also beneficial
1268 when a package may need many items disabled to run the test suite.
1269 Most packages use `pytest` or `unittest`, which is compatible with `pytest`,
1270 so you will most likely use `pytestCheckHook`.
1272 Using the example above, the analogous `pytestCheckHook` usage would be:
1276 nativeCheckInputs = [
1280 # requires additional data
1281 pytestFlagsArray = [
1283 "--ignore=tests/integration"
1292 disabledTestPaths = [
1293 "tests/test_failing.py"
1298 This is especially useful when tests need to be conditionally disabled,
1307 ] ++ lib.optionals (pythonAtLeast "3.8") [
1308 # broken due to python3.8 async changes
1310 ] ++ lib.optionals stdenv.buildPlatform.isDarwin [
1311 # can fail when building with other packages
1317 Trying to concatenate the related strings to disable tests in a regular
1318 [`checkPhase`](#ssec-check-phase) would be much harder to read. This also enables us to comment on
1319 why specific tests are disabled.
1321 #### Using pythonImportsCheck {#using-pythonimportscheck}
1323 Although unit tests are highly preferred to validate correctness of a package, not
1324 all packages have test suites that can be run easily, and some have none at all.
1325 To help ensure the package still works, [`pythonImportsCheck`](#using-pythonimportscheck) can attempt to import
1330 pythonImportsCheck = [
1337 roughly translates to:
1342 PYTHONPATH=$out/${python.sitePackages}:$PYTHONPATH
1343 python -c "import requests; import urllib"
1348 However, this is done in its own phase, and not dependent on whether [`doCheck = true;`](#var-stdenv-doCheck).
1350 This can also be useful in verifying that the package doesn't assume commonly
1351 present packages (e.g. `setuptools`).
1353 #### Using pythonRelaxDepsHook {#using-pythonrelaxdepshook}
1355 It is common for upstream to specify a range of versions for its package
1356 dependencies. This makes sense, since it ensures that the package will be built
1357 with a subset of packages that is well tested. However, this commonly causes
1358 issues when packaging in Nixpkgs, because the dependencies that this package
1359 may need are too new or old for the package to build correctly. We also cannot
1360 package multiple versions of the same package since this may cause conflicts
1363 One way to side step this issue is to relax the dependencies. This can be done
1364 by either removing the package version range or by removing the package
1365 declaration entirely. This can be done using the `pythonRelaxDepsHook` hook. For
1366 example, given the following `requirements.txt` file:
1382 pythonRemoveDeps = [
1388 which would result in the following `requirements.txt` file:
1395 Another option is to pass `true`, that will relax/remove all dependencies, for
1400 pythonRelaxDeps = true;
1404 which would result in the following `requirements.txt` file:
1412 In general you should always use `pythonRelaxDeps`, because `pythonRemoveDeps`
1413 will convert build errors into runtime errors. However `pythonRemoveDeps` may
1414 still be useful in exceptional cases, and also to remove dependencies wrongly
1415 declared by upstream (for example, declaring `black` as a runtime dependency
1416 instead of a dev dependency).
1418 Keep in mind that while the examples above are done with `requirements.txt`,
1419 `pythonRelaxDepsHook` works by modifying the resulting wheel file, so it should
1420 work with any of the [existing hooks](#setup-hooks).
1422 The `pythonRelaxDepsHook` has no effect on build time dependencies, such as
1423 those specified in `build-system`. If a package requires incompatible build
1424 time dependencies, they should be removed in `postPatch` through
1425 `substituteInPlace` or similar.
1427 For ease of use, both `buildPythonPackage` and `buildPythonApplication` will
1428 automatically add `pythonRelaxDepsHook` if either `pythonRelaxDeps` or
1429 `pythonRemoveDeps` is specified.
1431 #### Using unittestCheckHook {#using-unittestcheckhook}
1433 `unittestCheckHook` is a hook which will set up (or configure) a [`checkPhase`](#ssec-check-phase) to run `python -m unittest discover`:
1437 nativeCheckInputs = [
1441 unittestFlagsArray = [
1447 `pytest` is compatible with `unittest`, so in most cases you can use `pytestCheckHook` instead.
1449 #### Using sphinxHook {#using-sphinxhook}
1451 The `sphinxHook` is a helpful tool to build documentation and manpages
1452 using the popular Sphinx documentation generator.
1453 It is setup to automatically find common documentation source paths and
1454 render them using the default `html` style.
1463 nativeBuildInputs = [
1469 The hook will automatically build and install the artifact into the
1470 `doc` output, if it exists. It also provides an automatic diversion
1471 for the artifacts of the `man` builder into the `man` target.
1481 # Use multiple builders
1489 Overwrite `sphinxRoot` when the hook is unable to find your
1490 documentation source root.
1494 # Configure sphinxRoot for uncommon paths
1495 sphinxRoot = "weird/docs/path";
1499 The hook is also available to packages outside the python ecosystem by
1500 referencing it using `sphinxHook` from top-level.
1502 ### Organising your packages {#organising-your-packages}
1504 So far we discussed how you can use Python on Nix, and how you can develop with
1505 it. We've looked at how you write expressions to package Python packages, and we
1506 looked at how you can create environments in which specified packages are
1509 At some point you'll likely have multiple packages which you would
1510 like to be able to use in different projects. In order to minimise unnecessary
1511 duplication we now look at how you can maintain a repository with your
1512 own packages. The important functions here are `import` and `callPackage`.
1514 ### Including a derivation using `callPackage` {#including-a-derivation-using-callpackage}
1516 Earlier we created a Python environment using [`withPackages`](#python.withpackages-function), and included the
1517 `toolz` package via a `let` expression.
1518 Let's split the package definition from the environment definition.
1520 We first create a function that builds `toolz` in `~/path/to/toolz/release.nix`
1524 , buildPythonPackage
1529 buildPythonPackage rec {
1535 inherit pname version;
1536 hash = "sha256-CP3V73yWSArRHBLUct4hrNMjWZlvaaUlkpm1QP66RWA=";
1544 changelog = "https://github.com/pytoolz/toolz/releases/tag/${version}";
1545 homepage = "https://github.com/pytoolz/toolz/";
1546 description = "List processing tools and functional utilities";
1547 license = lib.licenses.bsd3;
1552 It takes an argument [`buildPythonPackage`](#buildpythonpackage-function). We now call this function using
1553 `callPackage` in the definition of our environment
1556 with import <nixpkgs> {};
1559 toolz = callPackage /path/to/toolz/release.nix {
1560 buildPythonPackage = python3Packages.buildPythonPackage;
1562 in python3.withPackages (ps: [
1569 Important to remember is that the Python version for which the package is made
1570 depends on the `python` derivation that is passed to [`buildPythonPackage`](#buildpythonpackage-function). Nix
1571 tries to automatically pass arguments when possible, which is why generally you
1572 don't explicitly define which `python` derivation should be used. In the above
1573 example we use [`buildPythonPackage`](#buildpythonpackage-function) that is part of the set `python3Packages`,
1574 and in this case the `python3` interpreter is automatically used.
1578 ### How to solve circular dependencies? {#how-to-solve-circular-dependencies}
1580 Consider the packages `A` and `B` that depend on each other. When packaging `B`,
1581 a solution is to override package `A` not to depend on `B` as an input. The same
1582 should also be done when packaging `A`.
1584 ### How to override a Python package? {#how-to-override-a-python-package}
1586 We can override the interpreter and pass `packageOverrides`. In the following
1587 example we rename the `pandas` package and build it.
1590 with import <nixpkgs> {};
1594 packageOverrides = self: super: {
1595 pandas = super.pandas.overridePythonAttrs(old: {name="foo";});
1597 in pkgs.python310.override {
1598 inherit packageOverrides;
1601 in python.withPackages (ps: [
1606 Using `nix-build` on this expression will build an environment that contains the
1607 package `pandas` but with the new name `foo`.
1609 All packages in the package set will use the renamed package. A typical use case
1610 is to switch to another version of a certain package. For example, in the
1611 Nixpkgs repository we have multiple versions of `django` and `scipy`. In the
1612 following example we use a different version of `scipy` and create an
1613 environment that uses it. All packages in the Python package set will now use
1614 the updated `scipy` version.
1617 with import <nixpkgs> {};
1620 packageOverrides = self: super: {
1621 scipy = super.scipy_0_17;
1623 in (pkgs.python310.override {
1624 inherit packageOverrides;
1625 }).withPackages (ps: [
1631 The requested package `blaze` depends on `pandas` which itself depends on `scipy`.
1633 If you want the whole of Nixpkgs to use your modifications, then you can use
1634 `overlays` as explained in this manual. In the following example we build a
1635 `inkscape` using a different version of `numpy`.
1639 pkgs = import <nixpkgs> {};
1640 newpkgs = import pkgs.path { overlays = [ (self: super: {
1642 packageOverrides = python-self: python-super: {
1643 numpy = python-super.numpy_1_18;
1645 in super.python310.override {inherit packageOverrides;};
1650 ### `python setup.py bdist_wheel` cannot create .whl {#python-setup.py-bdist_wheel-cannot-create-.whl}
1652 Executing `python setup.py bdist_wheel` in a `nix-shell`fails with
1655 ValueError: ZIP does not support timestamps before 1980
1658 This is because files from the Nix store (which have a timestamp of the UNIX
1659 epoch of January 1, 1970) are included in the .ZIP, but .ZIP archives follow the
1660 DOS convention of counting timestamps from 1980.
1662 The command `bdist_wheel` reads the `SOURCE_DATE_EPOCH` environment variable,
1663 which `nix-shell` sets to 1. Unsetting this variable or giving it a value
1664 corresponding to 1980 or later enables building wheels.
1666 Use 1980 as timestamp:
1669 nix-shell --run "SOURCE_DATE_EPOCH=315532800 python3 setup.py bdist_wheel"
1672 or the current time:
1675 nix-shell --run "SOURCE_DATE_EPOCH=$(date +%s) python3 setup.py bdist_wheel"
1678 or unset `SOURCE_DATE_EPOCH`:
1681 nix-shell --run "unset SOURCE_DATE_EPOCH; python3 setup.py bdist_wheel"
1684 ### `install_data` / `data_files` problems {#install_data-data_files-problems}
1686 If you get the following error:
1689 could not create '/nix/store/6l1bvljpy8gazlsw2aw9skwwp4pmvyxw-python-2.7.8/etc':
1693 This is a [known bug](https://github.com/pypa/setuptools/issues/130) in
1694 `setuptools`. Setuptools `install_data` does not respect `--prefix`. An example
1695 of such package using the feature is `pkgs/tools/X11/xpra/default.nix`.
1697 As workaround install it as an extra `preInstall` step:
1700 ${python.pythonOnBuildForHost.interpreter} setup.py install_data --install-dir=$out --root=$out
1701 sed -i '/ = data\_files/d' setup.py
1704 ### Rationale of non-existent global site-packages {#rationale-of-non-existent-global-site-packages}
1706 On most operating systems a global `site-packages` is maintained. This however
1707 becomes problematic if you want to run multiple Python versions or have multiple
1708 versions of certain libraries for your projects. Generally, you would solve such
1709 issues by creating virtual environments using `virtualenv`.
1711 On Nix each package has an isolated dependency tree which, in the case of
1712 Python, guarantees the right versions of the interpreter and libraries or
1713 packages are available. There is therefore no need to maintain a global `site-packages`.
1715 If you want to create a Python environment for development, then the recommended
1716 method is to use `nix-shell`, either with or without the [`python.buildEnv`](#python.buildenv-function)
1719 ### 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}
1721 While this approach is not very idiomatic from Nix perspective, it can still be
1722 useful when dealing with pre-existing projects or in situations where it's not
1723 feasible or desired to write derivations for all required dependencies.
1725 This is an example of a `default.nix` for a `nix-shell`, which allows to consume
1726 a virtual environment created by `venv`, and install Python modules through
1727 `pip` the traditional way.
1729 Create this `default.nix` file, together with a `requirements.txt` and
1730 execute `nix-shell`.
1733 with import <nixpkgs> { };
1736 pythonPackages = python3Packages;
1737 in pkgs.mkShell rec {
1738 name = "impurePythonEnv";
1739 venvDir = "./.venv";
1741 # A Python interpreter including the 'venv' module is required to bootstrap
1743 pythonPackages.python
1745 # This executes some shell code to initialize a venv in $venvDir before
1746 # dropping into the shell
1747 pythonPackages.venvShellHook
1749 # Those are dependencies that we would like to use from nixpkgs, which will
1750 # add them to PYTHONPATH and thus make them accessible from within the venv.
1751 pythonPackages.numpy
1752 pythonPackages.requests
1754 # In this particular example, in order to compile any binary extensions they may
1755 # require, the Python modules listed in the hypothetical requirements.txt need
1756 # the following packages to be installed locally:
1766 # Run this command, only after creating the virtual environment
1767 postVenvCreation = ''
1768 unset SOURCE_DATE_EPOCH
1769 pip install -r requirements.txt
1772 # Now we can execute any commands within the virtual environment.
1773 # This is optional and can be left out to run pip manually.
1775 # allow pip to install wheels
1776 unset SOURCE_DATE_EPOCH
1782 In case the supplied venvShellHook is insufficient, or when Python 2 support is
1783 needed, you can define your own shell hook and adapt to your needs like in the
1787 with import <nixpkgs> { };
1790 venvDir = "./.venv";
1791 pythonPackages = python3Packages;
1792 in pkgs.mkShell rec {
1793 name = "impurePythonEnv";
1795 pythonPackages.python
1796 # Needed when using python 2.7
1797 # pythonPackages.virtualenv
1801 # This is very close to how venvShellHook is implemented, but
1802 # adapted to use 'virtualenv'
1804 SOURCE_DATE_EPOCH=$(date +%s)
1806 if [ -d "${venvDir}" ]; then
1807 echo "Skipping venv creation, '${venvDir}' already exists"
1809 echo "Creating new venv environment in path: '${venvDir}'"
1810 # Note that the module venv was only introduced in python 3, so for 2.7
1811 # this needs to be replaced with a call to virtualenv
1812 ${pythonPackages.python.interpreter} -m venv "${venvDir}"
1815 # Under some circumstances it might be necessary to add your virtual
1816 # environment to PYTHONPATH, which you can do here too;
1817 # PYTHONPATH=$PWD/${venvDir}/${pythonPackages.python.sitePackages}/:$PYTHONPATH
1819 source "${venvDir}/bin/activate"
1821 # As in the previous example, this is optional.
1822 pip install -r requirements.txt
1827 Note that the `pip install` is an imperative action. So every time `nix-shell`
1828 is executed it will attempt to download the Python modules listed in
1829 requirements.txt. However these will be cached locally within the `virtualenv`
1830 folder and not downloaded again.
1832 ### How to override a Python package from `configuration.nix`? {#how-to-override-a-python-package-from-configuration.nix}
1834 If you need to change a package's attribute(s) from `configuration.nix` you could do:
1838 nixpkgs.config.packageOverrides = super: {
1839 python3 = super.python3.override {
1840 packageOverrides = python-self: python-super: {
1841 twisted = python-super.twisted.overridePythonAttrs (oldAttrs: {
1842 src = super.fetchPypi {
1844 version = "19.10.0";
1845 hash = "sha256-c5S6fycq5yKnTz2Wnc9Zm8TvCTvDkgOHSKSQ8XJKUV0=";
1846 extension = "tar.bz2";
1855 `python3Packages.twisted` is now globally overridden.
1856 All packages and also all NixOS services that reference `twisted`
1857 (such as `services.buildbot-worker`) now use the new definition.
1858 Note that `python-super` refers to the old package set and `python-self`
1859 to the new, overridden version.
1861 To modify only a Python package set instead of a whole Python derivation, use
1866 myPythonPackages = python3Packages.override {
1867 overrides = self: super: {
1874 ### How to override a Python package using overlays? {#how-to-override-a-python-package-using-overlays}
1876 Use the following overlay template:
1880 python = super.python.override {
1881 packageOverrides = python-self: python-super: {
1882 twisted = python-super.twisted.overrideAttrs (oldAttrs: {
1883 src = super.fetchPypi {
1885 version = "19.10.0";
1886 hash = "sha256-c5S6fycq5yKnTz2Wnc9Zm8TvCTvDkgOHSKSQ8XJKUV0=";
1887 extension = "tar.bz2";
1895 ### How to override a Python package for all Python versions using extensions? {#how-to-override-a-python-package-for-all-python-versions-using-extensions}
1897 The following overlay overrides the call to [`buildPythonPackage`](#buildpythonpackage-function) for the
1898 `foo` package for all interpreters by appending a Python extension to the
1899 `pythonPackagesExtensions` list of extensions.
1903 pythonPackagesExtensions = prev.pythonPackagesExtensions ++ [
1905 python-final: python-prev: {
1906 foo = python-prev.foo.overridePythonAttrs (oldAttrs: {
1915 ### How to use Intel’s MKL with numpy and scipy? {#how-to-use-intels-mkl-with-numpy-and-scipy}
1917 MKL can be configured using an overlay. See the section "[Using overlays to
1918 configure alternatives](#sec-overlays-alternatives-blas-lapack)".
1920 ### What inputs do `setup_requires`, `install_requires` and `tests_require` map to? {#what-inputs-do-setup_requires-install_requires-and-tests_require-map-to}
1922 In a `setup.py` or `setup.cfg` it is common to declare dependencies:
1924 * `setup_requires` corresponds to `build-system`
1925 * `install_requires` corresponds to `dependencies`
1926 * `tests_require` corresponds to [`nativeCheckInputs`](#var-stdenv-nativeCheckInputs)
1928 ### How to enable interpreter optimizations? {#optimizations}
1930 The Python interpreters are by default not built with optimizations enabled, because
1931 the builds are in that case not reproducible. To enable optimizations, override the
1932 interpreter of interest, e.g using
1936 pkgs = import ./. {};
1937 mypython = pkgs.python3.override {
1938 enableOptimizations = true;
1939 reproducibleBuild = false;
1945 ### How to add optional dependencies? {#python-optional-dependencies}
1947 Some packages define optional dependencies for additional features. With
1948 `setuptools` this is called `extras_require` and `flit` calls it
1949 `extras-require`, while PEP 621 calls these `optional-dependencies`.
1953 optional-dependencies = {
1954 complete = [ distributed ];
1959 and letting the package requiring the extra add the list to its dependencies
1965 ] ++ dask.optional-dependencies.complete;
1969 This method is using `passthru`, meaning that changing `optional-dependencies` of a package won't cause it to rebuild.
1971 Note this method is preferred over adding parameters to builders, as that can
1972 result in packages depending on different variants and thereby causing
1975 ### How to contribute a Python package to nixpkgs? {#tools}
1977 Packages inside nixpkgs must use the [`buildPythonPackage`](#buildpythonpackage-function) or [`buildPythonApplication`](#buildpythonapplication-function) function directly,
1978 because we can only provide security support for non-vendored dependencies.
1980 We recommend [nix-init](https://github.com/nix-community/nix-init) for creating new python packages within nixpkgs,
1981 as it already prefetches the source, parses dependencies for common formats and prefills most things in `meta`.
1983 See also [contributing section](#contributing).
1985 ### Are Python interpreters built deterministically? {#deterministic-builds}
1987 The Python interpreters are now built deterministically. Minor modifications had
1988 to be made to the interpreters in order to generate deterministic bytecode. This
1989 has security implications and is relevant for those using Python in a
1992 When the environment variable `DETERMINISTIC_BUILD` is set, all bytecode will
1993 have timestamp 1. The [`buildPythonPackage`](#buildpythonpackage-function) function sets `DETERMINISTIC_BUILD=1`
1994 and [PYTHONHASHSEED=0](https://docs.python.org/3.11/using/cmdline.html#envvar-PYTHONHASHSEED).
1995 Both are also exported in `nix-shell`.
1997 ### How to provide automatic tests to Python packages? {#automatic-tests}
1999 It is recommended to test packages as part of the build process.
2000 Source distributions (`sdist`) often include test files, but not always.
2002 The best practice today is to pass a test hook (e.g. pytestCheckHook, unittestCheckHook) into nativeCheckInputs.
2003 This will reconfigure the checkPhase to make use of that particular test framework.
2004 Occasionally packages don't make use of a common test framework, which may then require a custom checkPhase.
2006 #### Common issues {#common-issues}
2008 * Non-working tests can often be deselected. Most Python modules
2009 do follow the standard test protocol where the pytest runner can be used.
2010 `pytest` supports the `-k` and `--ignore` parameters to ignore test
2011 methods or classes as well as whole files. For `pytestCheckHook` these are
2012 conveniently exposed as `disabledTests` and `disabledTestPaths` respectively.
2015 buildPythonPackage {
2017 nativeCheckInputs = [
2026 disabledTestPaths = [
2032 * Tests that attempt to access `$HOME` can be fixed by using the following
2033 work-around before running tests (e.g. `preCheck`): `export HOME=$(mktemp -d)`
2034 * Compiling with Cython causes tests to fail with a `ModuleNotLoadedError`.
2035 This can be fixed with two changes in the derivation: 1) replacing `pytest` with
2036 `pytestCheckHook` and 2) adding a `preCheck` containing `cd $out` to run
2037 tests within the built output.
2039 ## Contributing {#contributing}
2041 ### Contributing guidelines {#contributing-guidelines}
2043 The following rules are desired to be respected:
2045 * Python libraries are called from `python-packages.nix` and packaged with
2046 [`buildPythonPackage`](#buildpythonpackage-function). The expression of a library should be in
2047 `pkgs/development/python-modules/<name>/default.nix`.
2048 * Python applications live outside of `python-packages.nix` and are packaged
2049 with [`buildPythonApplication`](#buildpythonapplication-function).
2050 * Make sure libraries build for all Python interpreters.
2051 If it fails to build on some Python versions, consider disabling them by setting `disable = pythonAtLeast "3.x"` along with a comment.
2052 * The two parameters, `pyproject` and `build-system` are set to avoid the legacy setuptools/distutils build.
2053 * Only unversioned attributes (e.g. `pydantic`, but not `pypdantic_1`) can be included in `dependencies`,
2054 since due to `PYTHONPATH` limitations we can only ever support a single version for libraries
2055 without running into duplicate module name conflicts.
2056 * The version restrictions of `dependencies` can be relaxed by [`pythonRelaxDepsHook`](#using-pythonrelaxdepshook).
2057 * Make sure the tests are enabled using for example [`pytestCheckHook`](#using-pytestcheckhook) and, in the case of
2058 libraries, are passing for all interpreters. If certain tests fail they can be
2059 disabled individually. Try to avoid disabling the tests altogether. In any
2060 case, when you disable tests, leave a comment explaining why.
2061 * `pythonImportsCheck` is set. This is still a good smoke test even if `pytestCheckHook` is set.
2062 * `meta.platforms` takes the default value in many cases.
2063 It does not need to be set explicitly unless the package requires a specific platform.
2064 * The file is formatted with `nixfmt-rfc-style`.
2065 * Commit names of Python libraries should reflect that they are Python
2066 libraries, so write for example `python311Packages.numpy: 1.11 -> 1.12`.
2067 It is highly recommended to specify the current default version to enable
2068 automatic build by ofborg.
2069 Note that `pythonPackages` is an alias for `python27Packages`.
2070 * Attribute names in `python-packages.nix` as well as `pname`s should match the
2071 library's name on PyPI, but be normalized according to [PEP
2072 0503](https://www.python.org/dev/peps/pep-0503/#normalized-names). This means
2073 that characters should be converted to lowercase and `.` and `_` should be
2074 replaced by a single `-` (foo-bar-baz instead of Foo__Bar.baz).
2075 If necessary, `pname` has to be given a different value within `fetchPypi`.
2076 * Packages from sources such as GitHub and GitLab that do not exist on PyPI
2077 should not use a name that is already used on PyPI. When possible, they should
2078 use the package repository name prefixed with the owner (e.g. organization) name
2079 and using a `-` as delimiter.
2080 * Attribute names in `python-packages.nix` should be sorted alphanumerically to
2081 avoid merge conflicts and ease locating attributes.
2083 This list is useful for reviewers as well as for self-checking when submitting packages.
2085 ## Package set maintenance {#python-package-set-maintenance}
2087 The whole Python package set has a lot of packages that do not see regular
2088 updates, because they either are a very fragile component in the Python
2089 ecosystem, like for example the `hypothesis` package, or packages that have
2090 no maintainer, so maintenance falls back to the package set maintainers.
2092 ### Updating packages in bulk {#python-package-bulk-updates}
2094 A tool to bulk-update numerous Python libraries is available in the
2095 repository at `maintainers/scripts/update-python-libraries`.
2097 It can quickly update minor or major versions for all packages selected
2098 and create update commits, and supports the `fetchPypi`, `fetchurl` and
2099 `fetchFromGitHub` fetchers. When updating lots of packages that are
2100 hosted on GitHub, exporting a `GITHUB_API_TOKEN` is highly recommended.
2102 Updating packages in bulk leads to lots of breakages, which is why a
2103 stabilization period on the `python-updates` branch is required.
2105 If a package is fragile and often breaks during these bulks updates, it
2106 may be reasonable to set `passthru.skipBulkUpdate = true` in the
2107 derivation. This decision should not be made on a whim and should
2108 always be supported by a qualifying comment.
2110 Once the branch is sufficiently stable it should normally be merged
2111 into the `staging` branch.
2113 An exemplary call to update all python libraries between minor versions
2117 $ maintainers/scripts/update-python-libraries --target minor --commit --use-pkgs-prefix pkgs/development/python-modules/**/default.nix
2120 ## CPython Update Schedule {#python-cpython-update-schedule}
2122 With [PEP 602](https://www.python.org/dev/peps/pep-0602/), CPython now
2123 follows a yearly release cadence. In nixpkgs, all supported interpreters
2124 are made available, but only the most recent two
2125 interpreters package sets are built; this is a compromise between being
2126 the latest interpreter, and what the majority of the Python packages support.
2128 New CPython interpreters are released in October. Generally, it takes some
2129 time for the majority of active Python projects to support the latest stable
2130 interpreter. To help ease the migration for Nixpkgs users
2131 between Python interpreters the schedule below will be used:
2135 | After YY.11 Release | Bump CPython package set window. The latest and previous latest stable should now be built. |
2136 | After YY.05 Release | Bump default CPython interpreter to latest stable. |
2138 In practice, this means that the Python community will have had a stable interpreter
2139 for ~2 months before attempting to update the package set. And this will
2140 allow for ~7 months for Python applications to support the latest interpreter.