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