Python

From NixOS Wiki
Revision as of 17:21, 6 May 2018 by imported>Krey

The Python packages available to the interpreter must be declared when installing Python.

To install, say Python 3 with pandas and requests, define a new package python-with-my-packages:

with pkgs;
let
  my-python-packages = python-packages: with python-packages; [
    pandas
    requests
    # other python packages you want
  ]; 
  python-with-my-packages = python3.withPackages my-python-packages
in ...

You can put python-with-my-packages into your environment.systemPackages for a system-wide installation, for instance.

There are several versions of Python available. Replace python3 with python2 or pypy in the above snippet according to your needs.

Explanation (optional)

We defined a function my-python-packages which takes as input a set python-packages and returns a list of attributes thereof.

Using alternative packages

We saw above how to install Python packages using nixpkgs. Since these are written by hand by nixpkgs maintainers, it isn't uncommon for packages you want to be missing or out of date.

pip

Add virtualenvwrapper to your list of Python packages above. Pure Python packages can be installed in a virtualenv using pip. The package pandas in the example below won't work.

Put your packages in a requirements.txt:

pandas
requests

Then setup the virtualenv:

virtualenv my-new-python-venv
source my-new-python-venv/bin/activate
pip install -r requirements.txt

conda

Install the package conda and run

conda-shell
conda-env create --name my-new-conda-env -f requirements.txt

Imperative use

It is also possible to use conda-install directly. On first use, run

conda-shell
conda-install

to set up conda in ~/.conda

pypi2nix

Contribution guidelines

Libraries

According to the official guidelines for python new package expressions for libraries should be placed in pkgs/development/python-modules/<name>/default.nix. Those expressions are then referenced from pkgs/top-level/python-packages.nix like in this example:

{
  aenum = callPackage ../development/python-modules/aenum { };
}

The reasoning behind this is the large size of pkgs/top-level/python-packages.nix. Unfortunately most libraries are still defined in-place in pkgs/top-level/python-packages.nix. If a change to library is necessary or an update is made, it is recommend to move the modified package out of pkgs/top-level/python-packages.nix.

Applications

Python applications instead should be referenced directly from pkgs/top-level/all-packages.nix.

The expression should take pythonPackages as one of the arguments, which guarantees that packages belong to the same set. For example:

{ lib
, pythonPackages
}:

with pythonPackages;

buildPythonApplication rec {
# ...

External Documentation