1# Python
2
3## User Guide
4
5### Using Python
6
7#### Overview
8
9Several versions of the Python interpreter are available on Nix, as well as a
10high amount of packages. The attribute `python` refers to the default
11interpreter, which is currently CPython 2.7. It is also possible to refer to
12specific versions, e.g. `python35` refers to CPython 3.5, and `pypy` refers to
13the default PyPy interpreter.
14
15Python is used a lot, and in different ways. This affects also how it is
16packaged. In the case of Python on Nix, an important distinction is made between
17whether the package is considered primarily an application, or whether it should
18be used as a library, i.e., of primary interest are the modules in
19`site-packages` that should be importable.
20
21In the Nixpkgs tree Python applications can be found throughout, depending on
22what they do, and are called from the main package set. Python libraries,
23however, are in separate sets, with one set per interpreter version.
24
25The interpreters have several common attributes. One of these attributes is
26`pkgs`, which is a package set of Python libraries for this specific
27interpreter. E.g., the `toolz` package corresponding to the default interpreter
28is `python.pkgs.toolz`, and the CPython 3.5 version is `python35.pkgs.toolz`.
29The main package set contains aliases to these package sets, e.g.
30`pythonPackages` refers to `python.pkgs` and `python35Packages` to
31`python35.pkgs`.
32
33#### Installing Python and packages
34
35The Nix and NixOS manuals explain how packages are generally installed. In the
36case of Python and Nix, it is important to make a distinction between whether the
37package is considered an application or a library.
38
39Applications on Nix are typically installed into your user
40profile imperatively using `nix-env -i`, and on NixOS declaratively by adding the
41package name to `environment.systemPackages` in `/etc/nixos/configuration.nix`.
42Dependencies such as libraries are automatically installed and should not be
43installed explicitly.
44
45The same goes for Python applications and libraries. Python applications can be
46installed in your profile. But Python libraries you would like to use for
47development cannot be installed, at least not individually, because they won't
48be able to find each other resulting in import errors. Instead, it is possible
49to create an environment with `python.buildEnv` or `python.withPackages` where
50the interpreter and other executables are able to find each other and all of the
51modules.
52
53In the following examples we create an environment with Python 3.5, `numpy` and
54`toolz`. As you may imagine, there is one limitation here, and that's that
55you can install only one environment at a time. You will notice the complaints
56about collisions when you try to install a second environment.
57
58##### Environment defined in separate `.nix` file
59
60Create a file, e.g. `build.nix`, with the following expression
61```nix
62with import <nixpkgs> {};
63
64python35.withPackages (ps: with ps; [ numpy toolz ])
65```
66and install it in your profile with
67```shell
68nix-env -if build.nix
69```
70Now you can use the Python interpreter, as well as the extra packages (`numpy`,
71`toolz`) that you added to the environment.
72
73##### Environment defined in `~/.config/nixpkgs/config.nix`
74
75If you prefer to, you could also add the environment as a package override to the Nixpkgs set, e.g.
76using `config.nix`,
77```nix
78{ # ...
79
80 packageOverrides = pkgs: with pkgs; {
81 myEnv = python35.withPackages (ps: with ps; [ numpy toolz ]);
82 };
83}
84```
85and install it in your profile with
86```shell
87nix-env -iA nixpkgs.myEnv
88```
89The environment is is installed by referring to the attribute, and considering
90the `nixpkgs` channel was used.
91
92##### Environment defined in `/etc/nixos/configuration.nix`
93
94For the sake of completeness, here's another example how to install the environment system-wide.
95
96```nix
97{ # ...
98
99 environment.systemPackages = with pkgs; [
100 (python35.withPackages(ps: with ps; [ numpy toolz ]))
101 ];
102}
103```
104
105#### Temporary Python environment with `nix-shell`
106
107The examples in the previous section showed how to install a Python environment
108into a profile. For development you may need to use multiple environments.
109`nix-shell` gives the possibility to temporarily load another environment, akin
110to `virtualenv`.
111
112There are two methods for loading a shell with Python packages. The first and recommended method
113is to create an environment with `python.buildEnv` or `python.withPackages` and load that. E.g.
114```sh
115$ nix-shell -p 'python35.withPackages(ps: with ps; [ numpy toolz ])'
116```
117opens a shell from which you can launch the interpreter
118```sh
119[nix-shell:~] python3
120```
121The other method, which is not recommended, does not create an environment and requires you to list the packages directly,
122
123```sh
124$ nix-shell -p python35.pkgs.numpy python35.pkgs.toolz
125```
126Again, it is possible to launch the interpreter from the shell.
127The Python interpreter has the attribute `pkgs` which contains all Python libraries for that specific interpreter.
128
129##### Load environment from `.nix` expression
130As explained in the Nix manual, `nix-shell` can also load an
131expression from a `.nix` file. Say we want to have Python 3.5, `numpy`
132and `toolz`, like before, in an environment. Consider a `shell.nix` file
133with
134```nix
135with import <nixpkgs> {};
136
137(python35.withPackages (ps: [ps.numpy ps.toolz])).env
138```
139Executing `nix-shell` gives you again a Nix shell from which you can run Python.
140
141What's happening here?
142
1431. We begin with importing the Nix Packages collections. `import <nixpkgs>` imports the `<nixpkgs>` function, `{}` calls it and the `with` statement brings all attributes of `nixpkgs` in the local scope. These attributes form the main package set.
1442. Then we create a Python 3.5 environment with the `withPackages` function.
1453. The `withPackages` function expects us to provide a function as an argument that takes the set of all python packages and returns a list of packages to include in the environment. Here, we select the packages `numpy` and `toolz` from the package set.
146
147To combine this with `mkShell` you can:
148
149```nix
150with import <nixpkgs> {};
151
152let
153 pythonEnv = python35.withPackages (ps: [
154 ps.numpy
155 ps.toolz
156 ]);
157in mkShell {
158 buildInputs = [
159 pythonEnv
160 hello
161 ];
162}
163```
164
165##### Execute command with `--run`
166A convenient option with `nix-shell` is the `--run`
167option, with which you can execute a command in the `nix-shell`. We can
168e.g. directly open a Python shell
169```sh
170$ nix-shell -p python35Packages.numpy python35Packages.toolz --run "python3"
171```
172or run a script
173```sh
174$ nix-shell -p python35Packages.numpy python35Packages.toolz --run "python3 myscript.py"
175```
176
177##### `nix-shell` as shebang
178In fact, for the second use case, there is a more convenient method. You can
179add a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) to your script
180specifying which dependencies `nix-shell` needs. With the following shebang, you
181can just execute `./myscript.py`, and it will make available all dependencies and
182run the script in the `python3` shell.
183
184```py
185#! /usr/bin/env nix-shell
186#! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy])"
187
188import numpy
189
190print(numpy.__version__)
191```
192
193### Developing with Python
194
195Now that you know how to get a working Python environment with Nix, it is time
196to go forward and start actually developing with Python. We will first have a
197look at how Python packages are packaged on Nix. Then, we will look at how you
198can use development mode with your code.
199
200#### Packaging a library
201
202With Nix all packages are built by functions. The main function in Nix for
203building Python libraries is `buildPythonPackage`. Let's see how we can build the
204`toolz` package.
205
206```nix
207{ lib, buildPythonPackage, fetchPypi }:
208
209buildPythonPackage rec {
210 pname = "toolz";
211 version = "0.7.4";
212
213 src = fetchPypi {
214 inherit pname version;
215 sha256 = "43c2c9e5e7a16b6c88ba3088a9bfc82f7db8e13378be7c78d6c14a5f8ed05afd";
216 };
217
218 doCheck = false;
219
220 meta = with lib; {
221 homepage = https://github.com/pytoolz/toolz;
222 description = "List processing tools and functional utilities";
223 license = licenses.bsd3;
224 maintainers = with maintainers; [ fridh ];
225 };
226}
227```
228
229What happens here? The function `buildPythonPackage` is called and as argument
230it accepts a set. In this case the set is a recursive set, `rec`. One of the
231arguments is the name of the package, which consists of a basename (generally
232following the name on PyPi) and a version. Another argument, `src` specifies the
233source, which in this case is fetched from PyPI using the helper function
234`fetchPypi`. The argument `doCheck` is used to set whether tests should be run
235when building the package. Furthermore, we specify some (optional) meta
236information. The output of the function is a derivation.
237
238An expression for `toolz` can be found in the Nixpkgs repository. As explained
239in the introduction of this Python section, a derivation of `toolz` is available
240for each interpreter version, e.g. `python35.pkgs.toolz` refers to the `toolz`
241derivation corresponding to the CPython 3.5 interpreter.
242The above example works when you're directly working on
243`pkgs/top-level/python-packages.nix` in the Nixpkgs repository. Often though,
244you will want to test a Nix expression outside of the Nixpkgs tree.
245
246The following expression creates a derivation for the `toolz` package,
247and adds it along with a `numpy` package to a Python environment.
248
249```nix
250with import <nixpkgs> {};
251
252( let
253 my_toolz = python35.pkgs.buildPythonPackage rec {
254 pname = "toolz";
255 version = "0.7.4";
256
257 src = python35.pkgs.fetchPypi {
258 inherit pname version;
259 sha256 = "43c2c9e5e7a16b6c88ba3088a9bfc82f7db8e13378be7c78d6c14a5f8ed05afd";
260 };
261
262 doCheck = false;
263
264 meta = {
265 homepage = "https://github.com/pytoolz/toolz/";
266 description = "List processing tools and functional utilities";
267 };
268 };
269
270 in python35.withPackages (ps: [ps.numpy my_toolz])
271).env
272```
273Executing `nix-shell` will result in an environment in which you can use
274Python 3.5 and the `toolz` package. As you can see we had to explicitly mention
275for which Python version we want to build a package.
276
277So, what did we do here? Well, we took the Nix expression that we used earlier
278to build a Python environment, and said that we wanted to include our own
279version of `toolz`, named `my_toolz`. To introduce our own package in the scope
280of `withPackages` we used a `let` expression. You can see that we used
281`ps.numpy` to select numpy from the nixpkgs package set (`ps`). We did not take
282`toolz` from the Nixpkgs package set this time, but instead took our own version
283that we introduced with the `let` expression.
284
285#### Handling dependencies
286
287Our example, `toolz`, does not have any dependencies on other Python packages or
288system libraries. According to the manual, `buildPythonPackage` uses the
289arguments `buildInputs` and `propagatedBuildInputs` to specify dependencies. If
290something is exclusively a build-time dependency, then the dependency should be
291included as a `buildInput`, but if it is (also) a runtime dependency, then it
292should be added to `propagatedBuildInputs`. Test dependencies are considered
293build-time dependencies and passed to `checkInputs`.
294
295The following example shows which arguments are given to `buildPythonPackage` in
296order to build [`datashape`](https://github.com/blaze/datashape).
297
298```nix
299{ lib, buildPythonPackage, fetchPypi, numpy, multipledispatch, dateutil, pytest }:
300
301buildPythonPackage rec {
302 pname = "datashape";
303 version = "0.4.7";
304
305 src = fetchPypi {
306 inherit pname version;
307 sha256 = "14b2ef766d4c9652ab813182e866f493475e65e558bed0822e38bf07bba1a278";
308 };
309
310 checkInputs = [ pytest ];
311 propagatedBuildInputs = [ numpy multipledispatch dateutil ];
312
313 meta = with lib; {
314 homepage = https://github.com/ContinuumIO/datashape;
315 description = "A data description language";
316 license = licenses.bsd2;
317 maintainers = with maintainers; [ fridh ];
318 };
319}
320```
321
322We can see several runtime dependencies, `numpy`, `multipledispatch`, and
323`dateutil`. Furthermore, we have one `checkInputs`, i.e. `pytest`. `pytest` is a
324test runner and is only used during the `checkPhase` and is therefore not added
325to `propagatedBuildInputs`.
326
327In the previous case we had only dependencies on other Python packages to consider.
328Occasionally you have also system libraries to consider. E.g., `lxml` provides
329Python bindings to `libxml2` and `libxslt`. These libraries are only required
330when building the bindings and are therefore added as `buildInputs`.
331
332```nix
333{ lib, pkgs, buildPythonPackage, fetchPypi }:
334
335buildPythonPackage rec {
336 pname = "lxml";
337 version = "3.4.4";
338
339 src = fetchPypi {
340 inherit pname version;
341 sha256 = "16a0fa97hym9ysdk3rmqz32xdjqmy4w34ld3rm3jf5viqjx65lxk";
342 };
343
344 buildInputs = [ pkgs.libxml2 pkgs.libxslt ];
345
346 meta = with lib; {
347 description = "Pythonic binding for the libxml2 and libxslt libraries";
348 homepage = https://lxml.de;
349 license = licenses.bsd3;
350 maintainers = with maintainers; [ sjourdois ];
351 };
352}
353```
354
355In this example `lxml` and Nix are able to work out exactly where the relevant
356files of the dependencies are. This is not always the case.
357
358The example below shows bindings to The Fastest Fourier Transform in the West, commonly known as
359FFTW. On Nix we have separate packages of FFTW for the different types of floats
360(`"single"`, `"double"`, `"long-double"`). The bindings need all three types,
361and therefore we add all three as `buildInputs`. The bindings don't expect to
362find each of them in a different folder, and therefore we have to set `LDFLAGS`
363and `CFLAGS`.
364
365```nix
366{ lib, pkgs, buildPythonPackage, fetchPypi, numpy, scipy }:
367
368buildPythonPackage rec {
369 pname = "pyFFTW";
370 version = "0.9.2";
371
372 src = fetchPypi {
373 inherit pname version;
374 sha256 = "f6bbb6afa93085409ab24885a1a3cdb8909f095a142f4d49e346f2bd1b789074";
375 };
376
377 buildInputs = [ pkgs.fftw pkgs.fftwFloat pkgs.fftwLongDouble];
378
379 propagatedBuildInputs = [ numpy scipy ];
380
381 # Tests cannot import pyfftw. pyfftw works fine though.
382 doCheck = false;
383
384 preConfigure = ''
385 export LDFLAGS="-L${pkgs.fftw.dev}/lib -L${pkgs.fftwFloat.out}/lib -L${pkgs.fftwLongDouble.out}/lib"
386 export CFLAGS="-I${pkgs.fftw.dev}/include -I${pkgs.fftwFloat.dev}/include -I${pkgs.fftwLongDouble.dev}/include"
387 '';
388
389 meta = with lib; {
390 description = "A pythonic wrapper around FFTW, the FFT library, presenting a unified interface for all the supported transforms";
391 homepage = http://hgomersall.github.com/pyFFTW;
392 license = with licenses; [ bsd2 bsd3 ];
393 maintainers = with maintainers; [ fridh ];
394 };
395}
396```
397Note also the line `doCheck = false;`, we explicitly disabled running the test-suite.
398
399
400#### Develop local package
401
402As a Python developer you're likely aware of [development mode](http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode) (`python setup.py develop`);
403instead of installing the package this command creates a special link to the project code.
404That way, you can run updated code without having to reinstall after each and every change you make.
405Development mode is also available. Let's see how you can use it.
406
407In the previous Nix expression the source was fetched from an url. We can also refer to a local source instead using
408`src = ./path/to/source/tree;`
409
410If we create a `shell.nix` file which calls `buildPythonPackage`, and if `src`
411is a local source, and if the local source has a `setup.py`, then development
412mode is activated.
413
414In the following example we create a simple environment that
415has a Python 3.5 version of our package in it, as well as its dependencies and
416other packages we like to have in the environment, all specified with `propagatedBuildInputs`.
417Indeed, we can just add any package we like to have in our environment to `propagatedBuildInputs`.
418
419```nix
420with import <nixpkgs> {};
421with python35Packages;
422
423buildPythonPackage rec {
424 name = "mypackage";
425 src = ./path/to/package/source;
426 propagatedBuildInputs = [ pytest numpy pkgs.libsndfile ];
427}
428```
429
430It is important to note that due to how development mode is implemented on Nix it is not possible to have multiple packages simultaneously in development mode.
431
432
433### Organising your packages
434
435So far we discussed how you can use Python on Nix, and how you can develop with
436it. We've looked at how you write expressions to package Python packages, and we
437looked at how you can create environments in which specified packages are
438available.
439
440At some point you'll likely have multiple packages which you would
441like to be able to use in different projects. In order to minimise unnecessary
442duplication we now look at how you can maintain a repository with your
443own packages. The important functions here are `import` and `callPackage`.
444
445### Including a derivation using `callPackage`
446
447Earlier we created a Python environment using `withPackages`, and included the
448`toolz` package via a `let` expression.
449Let's split the package definition from the environment definition.
450
451We first create a function that builds `toolz` in `~/path/to/toolz/release.nix`
452
453```nix
454{ lib, buildPythonPackage }:
455
456buildPythonPackage rec {
457 pname = "toolz";
458 version = "0.7.4";
459
460 src = fetchPypi {
461 inherit pname version;
462 sha256 = "43c2c9e5e7a16b6c88ba3088a9bfc82f7db8e13378be7c78d6c14a5f8ed05afd";
463 };
464
465 meta = with lib; {
466 homepage = "https://github.com/pytoolz/toolz/";
467 description = "List processing tools and functional utilities";
468 license = licenses.bsd3;
469 maintainers = with maintainers; [ fridh ];
470 };
471}
472```
473
474It takes an argument `buildPythonPackage`.
475We now call this function using `callPackage` in the definition of our environment
476
477```nix
478with import <nixpkgs> {};
479
480( let
481 toolz = callPackage /path/to/toolz/release.nix {
482 buildPythonPackage = python35Packages.buildPythonPackage;
483 };
484 in python35.withPackages (ps: [ ps.numpy toolz ])
485).env
486```
487
488Important to remember is that the Python version for which the package is made
489depends on the `python` derivation that is passed to `buildPythonPackage`. Nix
490tries to automatically pass arguments when possible, which is why generally you
491don't explicitly define which `python` derivation should be used. In the above
492example we use `buildPythonPackage` that is part of the set `python35Packages`,
493and in this case the `python35` interpreter is automatically used.
494
495## Reference
496
497### Interpreters
498
499Versions 2.7, 3.5, 3.6, 3.7 and 3.8 of the CPython interpreter are available as
500respectively `python27`, `python35`, `python36`, `python37` and `python38`. The aliases
501`python2` and `python3` correspond to respectively `python27` and
502`python37`. The default interpreter, `python`, maps to `python2`. The PyPy
503interpreters compatible with Python 2.7 and 3 are available as `pypy27` and
504`pypy3`, with aliases `pypy2` mapping to `pypy27` and `pypy` mapping to
505`pypy2`. The Nix expressions for the interpreters can be
506found in `pkgs/development/interpreters/python`.
507
508All packages depending on any Python interpreter get appended
509`out/{python.sitePackages}` to `$PYTHONPATH` if such directory
510exists.
511
512#### Missing `tkinter` module standard library
513
514To reduce closure size the `Tkinter`/`tkinter` is available as a separate package, `pythonPackages.tkinter`.
515
516#### Attributes on interpreters packages
517
518Each interpreter has the following attributes:
519
520- `libPrefix`. Name of the folder in `${python}/lib/` for corresponding interpreter.
521- `interpreter`. Alias for `${python}/bin/${executable}`.
522- `buildEnv`. Function to build python interpreter environments with extra packages bundled together. See section *python.buildEnv function* for usage and documentation.
523- `withPackages`. Simpler interface to `buildEnv`. See section *python.withPackages function* for usage and documentation.
524- `sitePackages`. Alias for `lib/${libPrefix}/site-packages`.
525- `executable`. Name of the interpreter executable, e.g. `python3.7`.
526- `pkgs`. Set of Python packages for that specific interpreter. The package set can be modified by overriding the interpreter and passing `packageOverrides`.
527
528### Building packages and applications
529
530Python libraries and applications that use `setuptools` or
531`distutils` are typically built with respectively the `buildPythonPackage` and
532`buildPythonApplication` functions. These two functions also support installing a `wheel`.
533
534All Python packages reside in `pkgs/top-level/python-packages.nix` and all
535applications elsewhere. In case a package is used as both a library and an application,
536then the package should be in `pkgs/top-level/python-packages.nix` since only those packages are made
537available for all interpreter versions. The preferred location for library expressions is in
538`pkgs/development/python-modules`. It is important that these packages are
539called from `pkgs/top-level/python-packages.nix` and not elsewhere, to guarantee
540the right version of the package is built.
541
542Based on the packages defined in `pkgs/top-level/python-packages.nix` an
543attribute set is created for each available Python interpreter. The available
544sets are
545
546* `pkgs.python27Packages`
547* `pkgs.python35Packages`
548* `pkgs.python36Packages`
549* `pkgs.python37Packages`
550* `pkgs.pypyPackages`
551
552and the aliases
553
554* `pkgs.python2Packages` pointing to `pkgs.python27Packages`
555* `pkgs.python3Packages` pointing to `pkgs.python37Packages`
556* `pkgs.pythonPackages` pointing to `pkgs.python2Packages`
557
558#### `buildPythonPackage` function
559
560The `buildPythonPackage` function is implemented in
561`pkgs/development/interpreters/python/mk-python-derivation`
562using setup hooks.
563
564The following is an example:
565```nix
566{ lib, buildPythonPackage, fetchPypi, hypothesis, setuptools_scm, attrs, py, setuptools, six, pluggy }:
567
568buildPythonPackage rec {
569 pname = "pytest";
570 version = "3.3.1";
571
572 src = fetchPypi {
573 inherit pname version;
574 sha256 = "cf8436dc59d8695346fcd3ab296de46425ecab00d64096cebe79fb51ecb2eb93";
575 };
576
577 postPatch = ''
578 # don't test bash builtins
579 rm testing/test_argcomplete.py
580 '';
581
582 checkInputs = [ hypothesis ];
583 nativeBuildInputs = [ setuptools_scm ];
584 propagatedBuildInputs = [ attrs py setuptools six pluggy ];
585
586 meta = with lib; {
587 maintainers = with maintainers; [ domenkozar lovek323 madjar lsix ];
588 description = "Framework for writing tests";
589 };
590}
591```
592
593The `buildPythonPackage` mainly does four things:
594
595* In the `buildPhase`, it calls `${python.interpreter} setup.py bdist_wheel` to
596 build a wheel binary zipfile.
597* In the `installPhase`, it installs the wheel file using `pip install *.whl`.
598* In the `postFixup` phase, the `wrapPythonPrograms` bash function is called to
599 wrap all programs in the `$out/bin/*` directory to include `$PATH`
600 environment variable and add dependent libraries to script's `sys.path`.
601* In the `installCheck` phase, `${python.interpreter} setup.py test` is ran.
602
603By default tests are run because `doCheck = true`. Test dependencies, like
604e.g. the test runner, should be added to `checkInputs`.
605
606By default `meta.platforms` is set to the same value
607as the interpreter unless overridden otherwise.
608
609##### `buildPythonPackage` parameters
610
611All parameters from `stdenv.mkDerivation` function are still supported. The following are specific to `buildPythonPackage`:
612
613* `catchConflicts ? true`: If `true`, abort package build if a package name appears more than once in dependency tree. Default is `true`.
614* `disabled` ? false: If `true`, package is not built for the particular Python interpreter version.
615* `dontWrapPythonPrograms ? false`: Skip wrapping of python programs.
616* `permitUserSite ? false`: Skip setting the `PYTHONNOUSERSITE` environment variable in wrapped programs.
617* `installFlags ? []`: A list of strings. Arguments to be passed to `pip install`. To pass options to `python setup.py install`, use `--install-option`. E.g., `installFlags=["--install-option='--cpp_implementation'"]`.
618* `format ? "setuptools"`: Format of the source. Valid options are `"setuptools"`, `"pyproject"`, `"flit"`, `"wheel"`, and `"other"`. `"setuptools"` is for when the source has a `setup.py` and `setuptools` is used to build a wheel, `flit`, in case `flit` should be used to build a wheel, and `wheel` in case a wheel is provided. Use `other` when a custom `buildPhase` and/or `installPhase` is needed.
619* `makeWrapperArgs ? []`: A list of strings. Arguments to be passed to `makeWrapper`, which wraps generated binaries. By default, the arguments to `makeWrapper` set `PATH` and `PYTHONPATH` environment variables before calling the binary. Additional arguments here can allow a developer to set environment variables which will be available when the binary is run. For example, `makeWrapperArgs = ["--set FOO BAR" "--set BAZ QUX"]`.
620* `namePrefix`: Prepends text to `${name}` parameter. In case of libraries, this defaults to `"python3.5-"` for Python 3.5, etc., and in case of applications to `""`.
621* `pythonPath ? []`: List of packages to be added into `$PYTHONPATH`. Packages in `pythonPath` are not propagated (contrary to `propagatedBuildInputs`).
622* `preShellHook`: Hook to execute commands before `shellHook`.
623* `postShellHook`: Hook to execute commands after `shellHook`.
624* `removeBinByteCode ? true`: Remove bytecode from `/bin`. Bytecode is only created when the filenames end with `.py`.
625* `setupPyGlobalFlags ? []`: List of flags passed to `setup.py` command.
626* `setupPyBuildFlags ? []`: List of flags passed to `setup.py build_ext` command.
627
628The `stdenv.mkDerivation` function accepts various parameters for describing build inputs (see "Specifying dependencies"). The following are of special
629interest for Python packages, either because these are primarily used, or because their behaviour is different:
630
631* `nativeBuildInputs ? []`: Build-time only dependencies. Typically executables as well as the items listed in `setup_requires`.
632* `buildInputs ? []`: Build and/or run-time dependencies that need to be be compiled for the host machine. Typically non-Python libraries which are being linked.
633* `checkInputs ? []`: Dependencies needed for running the `checkPhase`. These are added to `nativeBuildInputs` when `doCheck = true`. Items listed in `tests_require` go here.
634* `propagatedBuildInputs ? []`: Aside from propagating dependencies, `buildPythonPackage` also injects code into and wraps executables with the paths included in this list. Items listed in `install_requires` go here.
635
636##### Overriding Python packages
637
638The `buildPythonPackage` function has a `overridePythonAttrs` method that
639can be used to override the package. In the following example we create an
640environment where we have the `blaze` package using an older version of `pandas`.
641We override first the Python interpreter and pass
642`packageOverrides` which contains the overrides for packages in the package set.
643
644```nix
645with import <nixpkgs> {};
646
647(let
648 python = let
649 packageOverrides = self: super: {
650 pandas = super.pandas.overridePythonAttrs(old: rec {
651 version = "0.19.1";
652 src = super.fetchPypi {
653 pname = "pandas";
654 inherit version;
655 sha256 = "08blshqj9zj1wyjhhw3kl2vas75vhhicvv72flvf1z3jvapgw295";
656 };
657 });
658 };
659 in pkgs.python3.override {inherit packageOverrides; self = python;};
660
661in python.withPackages(ps: [ps.blaze])).env
662```
663
664#### `buildPythonApplication` function
665
666The `buildPythonApplication` function is practically the same as
667`buildPythonPackage`. The main purpose of this function is to build a Python
668package where one is interested only in the executables, and not importable
669modules. For that reason, when adding this package to a `python.buildEnv`, the
670modules won't be made available.
671
672Another difference is that `buildPythonPackage` by default prefixes the names of
673the packages with the version of the interpreter. Because this is irrelevant for
674applications, the prefix is omitted.
675
676When packaging a python application with `buildPythonApplication`, it should be
677called with `callPackage` and passed `python` or `pythonPackages` (possibly
678specifying an interpreter version), like this:
679
680```nix
681{ lib, python3Packages }:
682
683python3Packages.buildPythonApplication rec {
684 pname = "luigi";
685 version = "2.7.9";
686
687 src = python3Packages.fetchPypi {
688 inherit pname version;
689 sha256 = "035w8gqql36zlan0xjrzz9j4lh9hs0qrsgnbyw07qs7lnkvbdv9x";
690 };
691
692 propagatedBuildInputs = with python3Packages; [ tornado_4 python-daemon ];
693
694 meta = with lib; {
695 ...
696 };
697}
698```
699
700This is then added to `all-packages.nix` just as any other application would be.
701
702```nix
703luigi = callPackage ../applications/networking/cluster/luigi { };
704```
705
706Since the package is an application, a consumer doesn't need to care about
707python versions or modules, which is why they don't go in `pythonPackages`.
708
709#### `toPythonApplication` function
710
711A distinction is made between applications and libraries, however, sometimes a
712package is used as both. In this case the package is added as a library to
713`python-packages.nix` and as an application to `all-packages.nix`. To reduce
714duplication the `toPythonApplication` can be used to convert a library to an
715application.
716
717The Nix expression shall use `buildPythonPackage` and be called from
718`python-packages.nix`. A reference shall be created from `all-packages.nix` to
719the attribute in `python-packages.nix`, and the `toPythonApplication` shall be
720applied to the reference:
721```nix
722youtube-dl = with pythonPackages; toPythonApplication youtube-dl;
723```
724
725#### `toPythonModule` function
726
727In some cases, such as bindings, a package is created using
728`stdenv.mkDerivation` and added as attribute in `all-packages.nix`.
729The Python bindings should be made available from `python-packages.nix`.
730The `toPythonModule` function takes a derivation and makes certain Python-specific modifications.
731```nix
732opencv = toPythonModule (pkgs.opencv.override {
733 enablePython = true;
734 pythonPackages = self;
735});
736```
737Do pay attention to passing in the right Python version!
738
739#### `python.buildEnv` function
740
741Python environments can be created using the low-level `pkgs.buildEnv` function.
742This example shows how to create an environment that has the Pyramid Web Framework.
743Saving the following as `default.nix`
744```nix
745with import <nixpkgs> {};
746
747python.buildEnv.override {
748 extraLibs = [ pythonPackages.pyramid ];
749 ignoreCollisions = true;
750}
751```
752
753and running `nix-build` will create
754```
755/nix/store/cf1xhjwzmdki7fasgr4kz6di72ykicl5-python-2.7.8-env
756```
757
758with wrapped binaries in `bin/`.
759
760You can also use the `env` attribute to create local environments with needed
761packages installed. This is somewhat comparable to `virtualenv`. For example,
762running `nix-shell` with the following `shell.nix`
763```nix
764with import <nixpkgs> {};
765
766(python3.buildEnv.override {
767 extraLibs = with python3Packages; [ numpy requests ];
768}).env
769```
770
771will drop you into a shell where Python will have the
772specified packages in its path.
773
774
775##### `python.buildEnv` arguments
776
777* `extraLibs`: List of packages installed inside the environment.
778* `postBuild`: Shell command executed after the build of environment.
779* `ignoreCollisions`: Ignore file collisions inside the environment (default is `false`).
780* `permitUserSite`: Skip setting the `PYTHONNOUSERSITE` environment variable in wrapped binaries in the environment.
781
782#### `python.withPackages` function
783
784The `python.withPackages` function provides a simpler interface to the `python.buildEnv` functionality.
785It takes a function as an argument that is passed the set of python packages and returns the list
786of the packages to be included in the environment. Using the `withPackages` function, the previous
787example for the Pyramid Web Framework environment can be written like this:
788```nix
789with import <nixpkgs> {};
790
791python.withPackages (ps: [ps.pyramid])
792```
793
794`withPackages` passes the correct package set for the specific interpreter version as an
795argument to the function. In the above example, `ps` equals `pythonPackages`.
796But you can also easily switch to using python3:
797```nix
798with import <nixpkgs> {};
799
800python3.withPackages (ps: [ps.pyramid])
801```
802
803Now, `ps` is set to `python3Packages`, matching the version of the interpreter.
804
805As `python.withPackages` simply uses `python.buildEnv` under the hood, it also supports the `env`
806attribute. The `shell.nix` file from the previous section can thus be also written like this:
807```nix
808with import <nixpkgs> {};
809
810(python36.withPackages (ps: [ps.numpy ps.requests])).env
811```
812
813In contrast to `python.buildEnv`, `python.withPackages` does not support the more advanced options
814such as `ignoreCollisions = true` or `postBuild`. If you need them, you have to use `python.buildEnv`.
815
816Python 2 namespace packages may provide `__init__.py` that collide. In that case `python.buildEnv`
817should be used with `ignoreCollisions = true`.
818
819#### Setup hooks
820
821The following are setup hooks specifically for Python packages. Most of these are
822used in `buildPythonPackage`.
823
824- `eggUnpackhook` to move an egg to the correct folder so it can be installed with the `eggInstallHook`
825- `eggBuildHook` to skip building for eggs.
826- `eggInstallHook` to install eggs.
827- `flitBuildHook` to build a wheel using `flit`.
828- `pipBuildHook` to build a wheel using `pip` and PEP 517. Note a build system (e.g. `setuptools` or `flit`) should still be added as `nativeBuildInput`.
829- `pipInstallHook` to install wheels.
830- `pytestCheckHook` to run tests with `pytest`.
831- `pythonCatchConflictsHook` to check whether a Python package is not already existing.
832- `pythonImportsCheckHook` to check whether importing the listed modules works.
833- `pythonRemoveBinBytecode` to remove bytecode from the `/bin` folder.
834- `setuptoolsBuildHook` to build a wheel using `setuptools`.
835- `setuptoolsCheckHook` to run tests with `python setup.py test`.
836- `venvShellHook` to source a Python 3 `venv` at the `venvDir` location. A `venv` is created if it does not yet exist.
837- `wheelUnpackHook` to move a wheel to the correct folder so it can be installed with the `pipInstallHook`.
838
839### Development mode
840
841Development or editable mode is supported. To develop Python packages
842`buildPythonPackage` has additional logic inside `shellPhase` to run `pip
843install -e . --prefix $TMPDIR/`for the package.
844
845Warning: `shellPhase` is executed only if `setup.py` exists.
846
847Given a `default.nix`:
848```nix
849with import <nixpkgs> {};
850
851pythonPackages.buildPythonPackage {
852 name = "myproject";
853 buildInputs = with pythonPackages; [ pyramid ];
854
855 src = ./.;
856}
857```
858
859Running `nix-shell` with no arguments should give you
860the environment in which the package would be built with
861`nix-build`.
862
863Shortcut to setup environments with C headers/libraries and python packages:
864```shell
865nix-shell -p pythonPackages.pyramid zlib libjpeg git
866```
867
868Note: There is a boolean value `lib.inNixShell` set to `true` if nix-shell is invoked.
869
870### Tools
871
872Packages inside nixpkgs are written by hand. However many tools exist in
873community to help save time. No tool is preferred at the moment.
874
875- [pypi2nix](https://github.com/nix-community/pypi2nix): Generate Nix expressions for your Python project. Note that [sharing derivations from pypi2nix with nixpkgs is possible but not encouraged](https://github.com/nix-community/pypi2nix/issues/222#issuecomment-443497376).
876- [python2nix](https://github.com/proger/python2nix) by Vladimir Kirillov.
877
878### Deterministic builds
879
880The Python interpreters are now built deterministically.
881Minor modifications had to be made to the interpreters in order to generate
882deterministic bytecode. This has security implications and is relevant for
883those using Python in a `nix-shell`.
884
885When the environment variable `DETERMINISTIC_BUILD` is set, all bytecode will have timestamp 1.
886The `buildPythonPackage` function sets `DETERMINISTIC_BUILD=1` and
887[PYTHONHASHSEED=0](https://docs.python.org/3.5/using/cmdline.html#envvar-PYTHONHASHSEED).
888Both are also exported in `nix-shell`.
889
890
891### Automatic tests
892
893It is recommended to test packages as part of the build process.
894Source distributions (`sdist`) often include test files, but not always.
895
896By default the command `python setup.py test` is run as part of the
897`checkPhase`, but often it is necessary to pass a custom `checkPhase`. An
898example of such a situation is when `py.test` is used.
899
900#### Common issues
901
902- Non-working tests can often be deselected. By default `buildPythonPackage` runs `python setup.py test`.
903 Most python modules follows the standard test protocol where the pytest runner can be used instead.
904 `py.test` supports a `-k` parameter to ignore test methods or classes:
905
906 ```nix
907 buildPythonPackage {
908 # ...
909 # assumes the tests are located in tests
910 checkInputs = [ pytest ];
911 checkPhase = ''
912 py.test -k 'not function_name and not other_function' tests
913 '';
914 }
915 ```
916- Tests that attempt to access `$HOME` can be fixed by using the following work-around before running tests (e.g. `preCheck`): `export HOME=$(mktemp -d)`
917
918## FAQ
919
920### How to solve circular dependencies?
921
922Consider the packages `A` and `B` that depend on each other. When packaging `B`,
923a solution is to override package `A` not to depend on `B` as an input. The same
924should also be done when packaging `A`.
925
926### How to override a Python package?
927
928We can override the interpreter and pass `packageOverrides`.
929In the following example we rename the `pandas` package and build it.
930```nix
931with import <nixpkgs> {};
932
933(let
934 python = let
935 packageOverrides = self: super: {
936 pandas = super.pandas.overridePythonAttrs(old: {name="foo";});
937 };
938 in pkgs.python35.override {inherit packageOverrides;};
939
940in python.withPackages(ps: [ps.pandas])).env
941```
942Using `nix-build` on this expression will build an environment that contains the
943package `pandas` but with the new name `foo`.
944
945All packages in the package set will use the renamed package.
946A typical use case is to switch to another version of a certain package.
947For example, in the Nixpkgs repository we have multiple versions of `django` and `scipy`.
948In the following example we use a different version of `scipy` and create an environment that uses it.
949All packages in the Python package set will now use the updated `scipy` version.
950
951```nix
952with import <nixpkgs> {};
953
954( let
955 packageOverrides = self: super: {
956 scipy = super.scipy_0_17;
957 };
958 in (pkgs.python35.override {inherit packageOverrides;}).withPackages (ps: [ps.blaze])
959).env
960```
961The requested package `blaze` depends on `pandas` which itself depends on `scipy`.
962
963If you want the whole of Nixpkgs to use your modifications, then you can use `overlays`
964as explained in this manual. In the following example we build a `inkscape` using a different version of `numpy`.
965```nix
966let
967 pkgs = import <nixpkgs> {};
968 newpkgs = import pkgs.path { overlays = [ (pkgsself: pkgssuper: {
969 python27 = let
970 packageOverrides = self: super: {
971 numpy = super.numpy_1_10;
972 };
973 in pkgssuper.python27.override {inherit packageOverrides;};
974 } ) ]; };
975in newpkgs.inkscape
976```
977
978### `python setup.py bdist_wheel` cannot create .whl
979
980Executing `python setup.py bdist_wheel` in a `nix-shell `fails with
981```
982ValueError: ZIP does not support timestamps before 1980
983```
984
985This is because files from the Nix store (which have a timestamp of the UNIX epoch of January 1, 1970) are included in the .ZIP, but .ZIP archives follow the DOS convention of counting timestamps from 1980.
986
987The command `bdist_wheel` reads the `SOURCE_DATE_EPOCH` environment variable, which `nix-shell` sets to 1. Unsetting this variable or giving it a value corresponding to 1980 or later enables building wheels.
988
989Use 1980 as timestamp:
990```shell
991nix-shell --run "SOURCE_DATE_EPOCH=315532800 python3 setup.py bdist_wheel"
992```
993or the current time:
994```shell
995nix-shell --run "SOURCE_DATE_EPOCH=$(date +%s) python3 setup.py bdist_wheel"
996```
997or unset `SOURCE_DATE_EPOCH`:
998```shell
999nix-shell --run "unset SOURCE_DATE_EPOCH; python3 setup.py bdist_wheel"
1000```
1001
1002### `install_data` / `data_files` problems
1003
1004If you get the following error:
1005```
1006could not create '/nix/store/6l1bvljpy8gazlsw2aw9skwwp4pmvyxw-python-2.7.8/etc':
1007Permission denied
1008```
1009This is a [known bug](https://github.com/pypa/setuptools/issues/130) in `setuptools`.
1010Setuptools `install_data` does not respect `--prefix`. An example of such package using the feature is `pkgs/tools/X11/xpra/default.nix`.
1011As workaround install it as an extra `preInstall` step:
1012```shell
1013${python.interpreter} setup.py install_data --install-dir=$out --root=$out
1014sed -i '/ = data\_files/d' setup.py
1015```
1016
1017### Rationale of non-existent global site-packages
1018
1019On most operating systems a global `site-packages` is maintained. This however
1020becomes problematic if you want to run multiple Python versions or have multiple
1021versions of certain libraries for your projects. Generally, you would solve such
1022issues by creating virtual environments using `virtualenv`.
1023
1024On Nix each package has an isolated dependency tree which, in the case of
1025Python, guarantees the right versions of the interpreter and libraries or
1026packages are available. There is therefore no need to maintain a global `site-packages`.
1027
1028If you want to create a Python environment for development, then the recommended
1029method is to use `nix-shell`, either with or without the `python.buildEnv`
1030function.
1031
1032### How to consume python modules using pip in a virtual environment like I am used to on other Operating Systems?
1033
1034While this approach is not very idiomatic from Nix perspective, it can still be useful when dealing with pre-existing
1035projects or in situations where it's not feasible or desired to write derivations for all required dependencies.
1036
1037This is an example of a `default.nix` for a `nix-shell`, which allows to consume a virtual environment created by `venv`,
1038and install python modules through `pip` the traditional way.
1039
1040Create this `default.nix` file, together with a `requirements.txt` and simply execute `nix-shell`.
1041
1042```nix
1043with import <nixpkgs> { };
1044
1045let
1046 pythonPackages = python3Packages;
1047in pkgs.mkShell rec {
1048 name = "impurePythonEnv";
1049 venvDir = "./.venv";
1050 buildInputs = [
1051 # A python interpreter including the 'venv' module is required to bootstrap
1052 # the environment.
1053 pythonPackages.python
1054
1055 # This execute some shell code to initialize a venv in $venvDir before
1056 # dropping into the shell
1057 pythonPackages.venvShellHook
1058
1059 # Those are dependencies that we would like to use from nixpkgs, which will
1060 # add them to PYTHONPATH and thus make them accessible from within the venv.
1061 pythonPackages.numpy
1062 pythonPackages.requests
1063
1064 # In this particular example, in order to compile any binary extensions they may
1065 # require, the python modules listed in the hypothetical requirements.txt need
1066 # the following packages to be installed locally:
1067 taglib
1068 openssl
1069 git
1070 libxml2
1071 libxslt
1072 libzip
1073 zlib
1074 ];
1075
1076 # Now we can execute any commands within the virtual environment.
1077 # This is optional and can be left out to run pip manually.
1078 postShellHook = ''
1079 pip install -r requirements.txt
1080 '';
1081
1082}
1083```
1084
1085In case the supplied venvShellHook is insufficient, or when python 2 support is needed,
1086you can define your own shell hook and adapt to your needs like in the following example:
1087
1088```nix
1089with import <nixpkgs> { };
1090
1091let
1092 venvDir = "./.venv";
1093 pythonPackages = python3Packages;
1094in pkgs.mkShell rec {
1095 name = "impurePythonEnv";
1096 buildInputs = [
1097 pythonPackages.python
1098 # Needed when using python 2.7
1099 # pythonPackages.virtualenv
1100 # ...
1101 ];
1102
1103 # This is very close to how venvShellHook is implemented, but
1104 # adapted to use 'virtualenv'
1105 shellHook = ''
1106 SOURCE_DATE_EPOCH=$(date +%s)
1107
1108 if [ -d "${venvDir}" ]; then
1109 echo "Skipping venv creation, '${venvDir}' already exists"
1110 else
1111 echo "Creating new venv environment in path: '${venvDir}'"
1112 # Note that the module venv was only introduced in python 3, so for 2.7
1113 # this needs to be replaced with a call to virtualenv
1114 ${pythonPackages.python.interpreter} -m venv "${venvDir}"
1115 fi
1116
1117 # Under some circumstances it might be necessary to add your virtual
1118 # environment to PYTHONPATH, which you can do here too;
1119 # PYTHONPATH=$PWD/${venvDir}/${pythonPackages.python.sitePackages}/:$PYTHONPATH
1120
1121 source "${venvDir}/bin/activate"
1122
1123 # As in the previous example, this is optional.
1124 pip install -r requirements.txt
1125 '';
1126}
1127```
1128
1129Note that the `pip install` is an imperative action. So every time `nix-shell`
1130is executed it will attempt to download the python modules listed in
1131requirements.txt. However these will be cached locally within the `virtualenv`
1132folder and not downloaded again.
1133
1134### How to override a Python package from `configuration.nix`?
1135
1136If you need to change a package's attribute(s) from `configuration.nix` you could do:
1137
1138```nix
1139 nixpkgs.config.packageOverrides = super: {
1140 python = super.python.override {
1141 packageOverrides = python-self: python-super: {
1142 zerobin = python-super.zerobin.overrideAttrs (oldAttrs: {
1143 src = super.fetchgit {
1144 url = "https://github.com/sametmax/0bin";
1145 rev = "a344dbb18fe7a855d0742b9a1cede7ce423b34ec";
1146 sha256 = "16d769kmnrpbdr0ph0whyf4yff5df6zi4kmwx7sz1d3r6c8p6xji";
1147 };
1148 });
1149 };
1150 };
1151 };
1152```
1153
1154`pythonPackages.zerobin` is now globally overridden. All packages and also the
1155`zerobin` NixOS service use the new definition.
1156Note that `python-super` refers to the old package set and `python-self`
1157to the new, overridden version.
1158
1159To modify only a Python package set instead of a whole Python derivation, use this snippet:
1160
1161```nix
1162 myPythonPackages = pythonPackages.override {
1163 overrides = self: super: {
1164 zerobin = ...;
1165 };
1166 }
1167```
1168
1169### How to override a Python package using overlays?
1170
1171Use the following overlay template:
1172
1173```nix
1174self: super: {
1175 python = super.python.override {
1176 packageOverrides = python-self: python-super: {
1177 zerobin = python-super.zerobin.overrideAttrs (oldAttrs: {
1178 src = super.fetchgit {
1179 url = "https://github.com/sametmax/0bin";
1180 rev = "a344dbb18fe7a855d0742b9a1cede7ce423b34ec";
1181 sha256 = "16d769kmnrpbdr0ph0whyf4yff5df6zi4kmwx7sz1d3r6c8p6xji";
1182 };
1183 });
1184 };
1185 };
1186}
1187```
1188
1189### How to use Intel's MKL with numpy and scipy?
1190
1191A `site.cfg` is created that configures BLAS based on the `blas` parameter
1192of the `numpy` derivation. By passing in `mkl`, `numpy` and packages depending
1193on `numpy` will be built with `mkl`.
1194
1195The following is an overlay that configures `numpy` to use `mkl`:
1196```nix
1197self: super: {
1198 python37 = super.python37.override {
1199 packageOverrides = python-self: python-super: {
1200 numpy = python-super.numpy.override {
1201 blas = super.pkgs.mkl;
1202 };
1203 };
1204 };
1205}
1206```
1207
1208`mkl` requires an `openmp` implementation when running with multiple processors.
1209By default, `mkl` will use Intel's `iomp` implementation if no other is
1210specified, but this is a runtime-only dependency and binary compatible with the
1211LLVM implementation. To use that one instead, Intel recommends users set it with
1212`LD_PRELOAD`.
1213
1214Note that `mkl` is only available on `x86_64-{linux,darwin}` platforms;
1215moreover, Hydra is not building and distributing pre-compiled binaries using it.
1216
1217### What inputs do `setup_requires`, `install_requires` and `tests_require` map to?
1218
1219In a `setup.py` or `setup.cfg` it is common to declare dependencies:
1220
1221* `setup_requires` corresponds to `nativeBuildInputs`
1222* `install_requires` corresponds to `propagatedBuildInputs`
1223* `tests_require` corresponds to `checkInputs`
1224
1225## Contributing
1226
1227### Contributing guidelines
1228
1229Following rules are desired to be respected:
1230
1231* Python libraries are called from `python-packages.nix` and packaged with `buildPythonPackage`. The expression of a library should be in `pkgs/development/python-modules/<name>/default.nix`. Libraries in `pkgs/top-level/python-packages.nix` are sorted quasi-alphabetically to avoid merge conflicts.
1232* Python applications live outside of `python-packages.nix` and are packaged with `buildPythonApplication`.
1233* Make sure libraries build for all Python interpreters.
1234* By default we enable tests. Make sure the tests are found and, in the case of libraries, are passing for all interpreters. If certain tests fail they can be disabled individually. Try to avoid disabling the tests altogether. In any case, when you disable tests, leave a comment explaining why.
1235* Commit names of Python libraries should reflect that they are Python libraries, so write for example `pythonPackages.numpy: 1.11 -> 1.12`.
1236* Attribute names in `python-packages.nix` should be normalized according to [PEP 0503](https://www.python.org/dev/peps/pep-0503/#normalized-names).
1237 This means that characters should be converted to lowercase and `.` and `_` should be replaced by a single `-` (foo-bar-baz instead of Foo__Bar.baz )