Difference between revisions of "Python"

From NixOS Wiki
Jump to: navigation, search
(fix pkgs.mkShell)
m
 
(64 intermediate revisions by 38 users not shown)
Line 1: Line 1:
The Python packages available to the interpreter must be declared when installing Python.
+
{{warning|1=You are reading an article on the deprecated unofficial wiki. For the up to date version of this article, see https://wiki.nixos.org/wiki/Python.}}
 +
 
 +
== Installation ==
 +
 
 +
Python is a development package, and '''not meant to go in your system or home configuration'''.
 +
 
 +
If you need access to python for development, create a <code>shell.nix</code> for the specific project, along with any libraries needed:
 +
 
 +
<syntaxHighlight lang="nix">
 +
let
 +
  pkgs = import <nixpkgs> {};
 +
in pkgs.mkShell {
 +
  packages = [
 +
    (pkgs.python3.withPackages (python-pkgs: [
 +
      python-pkgs.pandas
 +
      python-pkgs.requests
 +
    ]))
 +
  ];
 +
}
 +
</syntaxHighlight>
 +
 
 +
Then run <code>nix-shell</code> to use the shell.
 +
 
 +
== 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. To create a custom Python environment with your own package(s), first create a derivation for each python package (look at examples in the <code>python-modules</code> subfolder in Nixpkgs). Then, use those derivations with <code>callPackage</code> as follows:
  
To install, say Python 3 with <code>pandas</code> and <code>requests</code>, define a new package <code>python-with-my-packages</code>:
 
 
<syntaxhighlight lang="nix">
 
<syntaxhighlight lang="nix">
 
with pkgs;
 
with pkgs;
 
let
 
let
   my-python-packages = python-packages: with python-packages; [
+
   my-python-package = ps: ps.callPackage ./my-package.nix {};
    pandas
+
   python-with-my-packages = python3.withPackages(ps: with ps; [
    requests
+
    (my-python-package ps)
    # other python packages you want
+
  ]);
  ];  
 
   python-with-my-packages = python3.withPackages my-python-packages;
 
 
in ...
 
in ...
 
</syntaxhighlight>
 
</syntaxhighlight>
  
You can put <code>python-with-my-packages</code> into your environment.systemPackages for a system-wide installation, for instance. Be mindful that <code>pythonX.withPackages</code> creates a <code>pythonX-Y.Z.W-env</code> package which is read only, so you can't use <code>pip</code> to install packages in, say, a virtual environment (as described below). Put <code>python</code> in your <code>configuration.nix</code> if you want to use the solution as described in the section "Python Virtual Environment".
+
=== Package and development shell for a python project ===
 +
 
 +
It is possible to use <code>buildPythonApplication</code> to package python applications. As explained in the nixpkgs manual, it uses the widely used `setup.py` file in order to package properly the application. We now show how to package a simple python application: a basic flask web server.
 +
 
 +
First, we write the python code, say in a file <code>web_interface.py</code>. Here we create a basic flask web server;
 +
<syntaxhighlight lang="python">
 +
#!/usr/bin/env python
 +
 
 +
from flask import Flask
 +
app = Flask(__name__)
 +
 
 +
@app.route('/')
 +
def hello_world():
 +
    return 'Hello, World!'
 +
 
 +
if __name__ == '__main__':
 +
    app.run(host="0.0.0.0", port=8080)
 +
</syntaxhighlight>
 +
 
 +
Then, we create the <code>setup.py</code> file, which basically explains which are the executables:
 +
<syntaxhighlight lang="python">
 +
#!/usr/bin/env python
  
There are several versions of Python available. Replace <code>python3</code> with <code>python2</code> or <code>pypy</code> in the above snippet according to your needs.
+
from setuptools import setup, find_packages
  
=== Explanation (optional) ===
+
setup(name='demo-flask-vuejs-rest',
 +
      version='1.0',
 +
      # Modules to import from other scripts:
 +
      packages=find_packages(),
 +
      # Executables
 +
      scripts=["web_interface.py"],
 +
    )
 +
</syntaxhighlight>
  
We defined a function <code>my-python-packages</code> which takes as input a set <code>python-packages</code> and returns a list of attributes thereof.
+
Finally, our nix derivation is now trivial: the file <code>derivation.nix</code> just needs to provide the python packages (here flask):
 +
<syntaxhighlight lang="nix">
 +
{ lib, python3Packages }:
 +
with python3Packages;
 +
buildPythonApplication {
 +
  pname = "demo-flask-vuejs-rest";
 +
  version = "1.0";
 +
 
 +
  propagatedBuildInputs = [ flask ];
 +
 
 +
  src = ./.;
 +
}
 +
</syntaxhighlight>
 +
 
 +
and we can now load this derivation from our file <code>default.nix</code>:
 +
<syntaxhighlight lang="nix">
 +
{ pkgs ? import <nixpkgs> {} }:
 +
pkgs.callPackage ./derivation.nix {}
 +
</syntaxhighlight>
  
== Using alternative packages ==
+
We can now build with:
 +
<syntaxhighlight lang=console>
 +
$ nix-build
 +
[...]
 +
$ ./result/bin/web_interface.py
 +
* Serving Flask app ".web_interface" (lazy loading)
 +
[...]
 +
</syntaxhighlight>
 +
or just enter a nix-shell, and directly execute your program or python if it's easier to develop:
 +
<syntaxhighlight lang=console>
 +
$ nix-shell
 +
[...]
 +
[nix-shell]$ chmod +x web_interface.py
 +
[nix-shell]$ ./web_interface.py
 +
* Serving Flask app "web_interface" (lazy loading)
 +
[...]
  
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.
+
[nix-shell]$ python
 +
Python 3.8.7 (default, Dec 21 2020, 17:18:55)
 +
[GCC 10.2.0] on linux
 +
Type "help", "copyright", "credits" or "license" for more information.
 +
>>> import flask
 +
>>>
 +
</syntaxhighlight>
  
 
=== Python virtual environment ===
 
=== Python virtual environment ===
Line 31: Line 120:
 
The Python 3 venv approach has the benefit of forcing you to choose a specific version of the Python 3 interpreter that should be used to create the virtual environment. This avoids any confusion as to which Python installation the new environment is based on.
 
The Python 3 venv approach has the benefit of forcing you to choose a specific version of the Python 3 interpreter that should be used to create the virtual environment. This avoids any confusion as to which Python installation the new environment is based on.
  
From Python 3.3 to 3.4, the recommended way to create a virtual environment was to use the pyvenv command-line tool that also comes included with your Python 3 installation by default. But on 3.6 and above, python3 -m venv is the way to go.
+
Recommended usage:
 +
* Python 3.3-3.4 (old): the recommended way to create a virtual environment was to use the pyvenv command-line tool that also comes included with your Python 3 installation by default.  
 +
* Python 3.6+: <code>python3 -m venv</code> is the way to go.
  
 
Put your packages in a requirements.txt:
 
Put your packages in a requirements.txt:
<syntaxhighlight>
+
<syntaxhighlight lang=text>
 
pandas
 
pandas
 
requests
 
requests
Line 45: Line 136:
 
pip install -r requirements.txt
 
pip install -r requirements.txt
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Installing packages with <code>pip</code> that need to compile code or use C libraries will sometimes fail due to not finding dependencies in the expected places. In that case you can use <code>buildFHSUserEnv</code> to make yourself a sandbox that appears like a more typical Linux install (or you can also certainly use <code>nix-ld</code> to turn your whole system into a more standard Linux distribution). For example if you were working with machine learning code you could use:
 +
 +
<syntaxhighlight lang="nix">
 +
{ pkgs ? import <nixpkgs> {} }:
 +
(pkgs.buildFHSUserEnv {
 +
  name = "pipzone";
 +
  targetPkgs = pkgs: (with pkgs; [
 +
    python39
 +
    python39Packages.pip
 +
    python39Packages.virtualenv
 +
    cudaPackages.cudatoolkit
 +
  ]);
 +
  runScript = "bash";
 +
}).env
 +
</syntaxhighlight>
 +
 +
In <code>pip-shell.nix</code>, and enter the environment with:
 +
 +
<syntaxhighlight lang="shell">
 +
nix-shell pip-shell.nix
 +
virtualenv venv
 +
source venv/bin/activate
 +
</syntaxhighlight>
 +
 +
==== Virtualenv without nix on NixOS ====
 +
Another option is to follow the [https://gist.github.com/GuillaumeDesforges/7d66cf0f63038724acf06f17331c9280 fix-python gist] to setup a virtualenv without explicitly entering a nix shell.
  
 
=== Emulating virtualenv with nix-shell ===
 
=== Emulating virtualenv with nix-shell ===
 
In some cases virtualenv fails to install a library because it requires patching on NixOS (example 1, example 2, general issue). In this cases it is better to replace those libraries with ones from Nix.
 
In some cases virtualenv fails to install a library because it requires patching on NixOS (example 1, example 2, general issue). In this cases it is better to replace those libraries with ones from Nix.
  
Let's say, that nanomsg library fails to install in virtualenv. Then write a `default.nix` file:
+
Let's say, that nanomsg library fails to install in virtualenv. Then write a <code>shell.nix</code> file:
  
 
<syntaxhighlight lang="nix">
 
<syntaxhighlight lang="nix">
let pkgs = import <nixpkgs> {};
+
let
    nanomsg-py = .... build expression for this python library;
+
  pkgs = import <nixpkgs> {};
 +
  nanomsg-py = ...build expression for this python library...;
 
in pkgs.mkShell {
 
in pkgs.mkShell {
 
   buildInputs = [
 
   buildInputs = [
     pkgs.pythonPackages.pip
+
     pkgs.python3
 +
    pkgs.python3.pkgs.requests
 
     nanomsg-py
 
     nanomsg-py
 
   ];
 
   ];
 
   shellHook = ''
 
   shellHook = ''
            alias pip="PIP_PREFIX='$(pwd)/_build/pip_packages' \pip"
+
    # Tells pip to put packages into $PIP_PREFIX instead of the usual locations.
            export PYTHONPATH="$(pwd)/_build/pip_packages/lib/python2.7/site-packages:$PYTHONPATH"
+
    # See https://pip.pypa.io/en/stable/user_guide/#environment-variables.
            unset SOURCE_DATE_EPOCH
+
    export PIP_PREFIX=$(pwd)/_build/pip_packages
 +
    export PYTHONPATH="$PIP_PREFIX/${pkgs.python3.sitePackages}:$PYTHONPATH"
 +
    export PATH="$PIP_PREFIX/bin:$PATH"
 +
    unset SOURCE_DATE_EPOCH
 
   '';
 
   '';
 
}
 
}
Line 70: Line 193:
  
 
Discussion and consequences of this approach are in PR https://github.com/NixOS/nixpkgs/pull/55265.
 
Discussion and consequences of this approach are in PR https://github.com/NixOS/nixpkgs/pull/55265.
 +
 +
=== micromamba ===
 +
 +
Install the <code>micromamba</code> package.
 +
You can create environments and install packages as [https://github.com/mamba-org/mamba#micromamba documented by micromamba] e.g.
 +
<syntaxhighlight lang="shell">
 +
micromamba create -n my-environment python=3.9 numpy=1.23.0 -c conda-forge
 +
</syntaxhighlight>
 +
 +
To activate an environment you will need a [https://nixos.org/manual/nixpkgs/stable/#sec-fhs-environments FHS environment] e.g.:
 +
<syntaxhighlight lang="console">
 +
$ nix-shell -E 'with import <nixpkgs> {}; (pkgs.buildFHSUserEnv { name = "fhs"; }).env'
 +
$ eval "$(micromamba shell hook -s bash)"
 +
$ micromamba activate my-environment
 +
$ python
 +
>>> import numpy as np
 +
</syntaxhighlight>
 +
 +
Eventually you'll probably want to put this in a shell.nix so you won't have to type all that stuff every time e.g.:
 +
<syntaxhighlight lang="shell">
 +
{ pkgs ? import <nixpkgs> {}}:
 +
let
 +
  fhs = pkgs.buildFHSUserEnv {
 +
    name = "my-fhs-environment";
 +
 +
    targetPkgs = _: [
 +
      pkgs.micromamba
 +
    ];
 +
 +
    profile = ''
 +
      set -e
 +
      eval "$(micromamba shell hook --shell=posix)"
 +
      export MAMBA_ROOT_PREFIX=${builtins.getEnv "PWD"}/.mamba
 +
      micromamba create -q -n my-mamba-environment
 +
      micromamba activate my-mamba-environment
 +
      micromamba install --yes -f conda-requirements.txt -c conda-forge
 +
      set +e
 +
    '';
 +
  };
 +
in fhs.env
 +
</syntaxhighlight>
 +
 +
 
=== conda ===
 
=== conda ===
  
Line 89: Line 255:
 
to set up conda in <code>~/.conda</code>
 
to set up conda in <code>~/.conda</code>
  
=== pypi2nix ===
+
=== pip2nix ===
 +
[https://github.com/nix-community/pip2nix pip2nix] generate nix expressions for Python packages.
 +
 
 +
Also see the [https://github.com/nix-community/pypi2nix pypi2nix]-project (abandoned in 2019).
  
 
== Contribution guidelines ==
 
== Contribution guidelines ==
Line 130: Line 299:
  
 
Or, if you want to use matplotlib interactively:
 
Or, if you want to use matplotlib interactively:
<syntaxhighlight lang=shell>
+
<syntaxhighlight lang=console>
$ nix-shell -p gobjectIntrospection gtk3 'python36.withPackages(ps : with ps; [ matplotlib pygobject3 ipython ])'
+
$ nix-shell -p gobject-introspection gtk3 'python36.withPackages(ps : with ps; [ matplotlib pygobject3 ipython ])'
 
$ ipython
 
$ ipython
 
</syntaxhighlight>
 
</syntaxhighlight>
Line 144: Line 313:
 
You can also set <code>backend : GTK3Agg</code> in your <code>~/.config/matplotlib/matplotlibrc</code> file to avoid having to call <code>matplotlib.use('gtk3agg')</code>.
 
You can also set <code>backend : GTK3Agg</code> in your <code>~/.config/matplotlib/matplotlibrc</code> file to avoid having to call <code>matplotlib.use('gtk3agg')</code>.
  
== External Documentation ==
+
== Performance ==
 +
The derivation of cPython that is available via <code>nixpkgs</code> does not contain optimizations enabled, specifically Profile Guided Optimization (PGO) and Link Time Optimization (LTO). See [https://docs.python.org/3/using/configure.html#performance-options Configuring Python 3.1.3. Performance options]
 +
Additionally, when you compile something within <code>nix-shell</code> or a derivation; by default there are security hardening flags passed to the compiler which do have a small performance impact.
 +
 
 +
As of the time of this writing; these optimizations cause Python builds to be non-reproducible and increase install times for the derivation. For a more detailed overview of the trials and tabulations of discovering the performance regression; see [https://discourse.nixos.org/t/why-is-the-nix-compiled-python-slower/18717 Why is the nix-compiled Python slower?] thread on the nix forums.
 +
 
 +
 
 +
=== Regression ===
 +
With the <code>nixpkgs</code> version of Python you can expect anywhere from a 30-40% regression on synthetic benchmarks. For example:
 +
<syntaxhighlight lang=python>## Ubuntu's Python 3.8
 +
username:dir$ python3.8 -c "import timeit; print(timeit.Timer('for i in range(100): oct(i)', 'gc.enable()').repeat(5))"
 +
[7.831622750498354, 7.82998560462147, 7.830805554986, 7.823807033710182, 7.84282516874373]
 +
 
 +
## nix-shell's Python 3.8
 +
[nix-shell:~/src]$ python3.8 -c "import timeit; print(timeit.Timer('for i in range(100): oct(i)', 'gc.enable()').repeat(5))"
 +
[10.431915327906609, 10.435049421153963, 10.449542525224388, 10.440207410603762, 10.431304694153368]
 +
</syntaxhighlight>
 +
 
 +
However, synthetic benchmarks are not a reflection of a real-world use case. In most situations, the performance difference between optimized & non-optimized interpreters is minimal. For example; using <code>pylint</code> with a significant number of custom linters to go scan a very large Python codebase (>6000 files) resulted in only a 5.5% difference, instead of 40%. Other workflows that were not performance sensitive saw no impact to their run times.
 +
 
 +
 
 +
=== Possible Optimizations ===
 +
If you run code that heavily depends on Python performance (data science, machine learning), and you want to have the most performant Python interpreter possible, here are some possible things you can do:
 +
 
 +
* Enable the <code>enableOptimizations</code> flag for your Python derivation. [https://discourse.nixos.org/t/why-is-the-nix-compiled-python-slower/18717/10 Example] Do note that this will cause you to compile Python the first time that you run it; which will take a few minutes.
 +
* Switch to a newer version of Python. In the example above, going from 3.8 to 3.10 yielded an average 7.5% performance improvement; but this is only a single benchmark. Switching versions most likely won't make all your code 7.5% faster.
 +
* Disable hardening, although this only yields a small performance boost; and it has impacts beyond Python code. [https://nixos.org/manual/nixpkgs/stable/#sec-hardening-in-nixpkgs Hardening in Nixpkgs]
 +
 
 +
'''Ultimately, it is up to your use case to determine if you need an optimized version of the Python interpreter. We encourage you to benchmark and test your code to determine if this is something that would benefit you.'''
 +
 
 +
== Troubleshotting ==
 +
=== My module cannot be imported ===
 +
 
 +
If you are unable to do `import yourmodule` there are a number of reasons that could explain that.
 +
 
 +
First, make sure that you installed/added your module to python. Typically you would use something like <code> (python3.withPackages (ps: with ps; [ yourmodule ]))</code> in the list of installed applications.
 +
 
 +
It is also still possible (e.g. when using nix-shell) that you aren't using the python interpreter you want because another package provides its own <code>python3.withPackages</code> in buildInputs, for example, yosys. In this case, you should either include that package (or all needed packages) in your withPackages list to only have a single Python interpreter. Or you can change the order of your packages, such that the <code>python3.withPackages</code> comes first, and becomes the Python interpreter that you get.
 +
 
 +
If you packaged yourself your application, make sure to use <code>buildPythonPackage</code> and **not** <code>buildPythonApplication</code> or <code>stdenv.mkDerivation</code>. The reason is that <code>python3.withPackages</code> [https://github.com/NixOS/nixpkgs/blob/91d1eb9f2a9c4e3c9d68a59f6c0cada8c63d5340/pkgs/top-level/python-packages.nix#L57 filters] the packages to check that they are built using the appropriate python interpreter: this is done by verifying that the derivation has a <code>pythonModule</code> attribute and only buildPythonPackage [https://github.com/NixOS/nixpkgs/blob/91d1eb9f2a9c4e3c9d68a59f6c0cada8c63d5340/pkgs/top-level/python-packages.nix#L43 sets this value] (passthru [https://github.com/NixOS/nixpkgs/blob/91d1eb9f2a9c4e3c9d68a59f6c0cada8c63d5340/pkgs/top-level/python-packages.nix#L75 here]) thanks to, notably <code>passthru = { pythonModule = python; }</code>. If you used <code>stdenv.mkDerivation</code> then you can maybe set this value manually, but it's safer to simply use <code>buildPythonPackage  {format = "other"; … your derivation …}</code> instead of <code>mkDerivation</code>.
 +
 
 +
== See also ==
  
* [https://nixos.org/nixpkgs/manual/#python Python user guide in nixpkgs manual]
+
* [[Packaging/Python]]
 +
* [https://ryantm.github.io/nixpkgs/languages-frameworks/python/#python Python user guide in nixpkgs manual]
 +
* [https://github.com/cachix/nixpkgs-python Nixpgs-python: A repo providing every version of python as flake ]
 +
[[Category:Languages]]

Latest revision as of 16:45, 5 April 2024

Warning: You are reading an article on the deprecated unofficial wiki. For the up to date version of this article, see https://wiki.nixos.org/wiki/Python.

Installation

Python is a development package, and not meant to go in your system or home configuration.

If you need access to python for development, create a shell.nix for the specific project, along with any libraries needed:

let
  pkgs = import <nixpkgs> {};
in pkgs.mkShell {
  packages = [
    (pkgs.python3.withPackages (python-pkgs: [
      python-pkgs.pandas
      python-pkgs.requests
    ]))
  ];
}

Then run nix-shell to use the shell.

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. To create a custom Python environment with your own package(s), first create a derivation for each python package (look at examples in the python-modules subfolder in Nixpkgs). Then, use those derivations with callPackage as follows:

with pkgs;
let
  my-python-package = ps: ps.callPackage ./my-package.nix {};
  python-with-my-packages = python3.withPackages(ps: with ps; [
    (my-python-package ps)
  ]);
in ...

Package and development shell for a python project

It is possible to use buildPythonApplication to package python applications. As explained in the nixpkgs manual, it uses the widely used `setup.py` file in order to package properly the application. We now show how to package a simple python application: a basic flask web server.

First, we write the python code, say in a file web_interface.py. Here we create a basic flask web server;

#!/usr/bin/env python

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080)

Then, we create the setup.py file, which basically explains which are the executables:

#!/usr/bin/env python

from setuptools import setup, find_packages

setup(name='demo-flask-vuejs-rest',
      version='1.0',
      # Modules to import from other scripts:
      packages=find_packages(),
      # Executables
      scripts=["web_interface.py"],
     )

Finally, our nix derivation is now trivial: the file derivation.nix just needs to provide the python packages (here flask):

{ lib, python3Packages }:
with python3Packages;
buildPythonApplication {
  pname = "demo-flask-vuejs-rest";
  version = "1.0";

  propagatedBuildInputs = [ flask ];

  src = ./.;
}

and we can now load this derivation from our file default.nix:

{ pkgs ? import <nixpkgs> {} }:
pkgs.callPackage ./derivation.nix {}

We can now build with:

$ nix-build
[...]
$ ./result/bin/web_interface.py 
 * Serving Flask app ".web_interface" (lazy loading)
 [...]

or just enter a nix-shell, and directly execute your program or python if it's easier to develop:

$ nix-shell
[...]
[nix-shell]$ chmod +x web_interface.py
[nix-shell]$ ./web_interface.py 
 * Serving Flask app "web_interface" (lazy loading)
[...]

[nix-shell]$ python
Python 3.8.7 (default, Dec 21 2020, 17:18:55) 
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask
>>>

Python virtual environment

Starting from Python 3 virtual environment is natively supported. The Python 3 venv approach has the benefit of forcing you to choose a specific version of the Python 3 interpreter that should be used to create the virtual environment. This avoids any confusion as to which Python installation the new environment is based on.

Recommended usage:

  • Python 3.3-3.4 (old): the recommended way to create a virtual environment was to use the pyvenv command-line tool that also comes included with your Python 3 installation by default.
  • Python 3.6+: python3 -m venv is the way to go.

Put your packages in a requirements.txt:

pandas
requests

Then setup the virtualenv:

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Installing packages with pip that need to compile code or use C libraries will sometimes fail due to not finding dependencies in the expected places. In that case you can use buildFHSUserEnv to make yourself a sandbox that appears like a more typical Linux install (or you can also certainly use nix-ld to turn your whole system into a more standard Linux distribution). For example if you were working with machine learning code you could use:

{ pkgs ? import <nixpkgs> {} }:
(pkgs.buildFHSUserEnv {
  name = "pipzone";
  targetPkgs = pkgs: (with pkgs; [
    python39
    python39Packages.pip
    python39Packages.virtualenv
    cudaPackages.cudatoolkit
  ]);
  runScript = "bash";
}).env

In pip-shell.nix, and enter the environment with:

nix-shell pip-shell.nix
virtualenv venv
source venv/bin/activate

Virtualenv without nix on NixOS

Another option is to follow the fix-python gist to setup a virtualenv without explicitly entering a nix shell.

Emulating virtualenv with nix-shell

In some cases virtualenv fails to install a library because it requires patching on NixOS (example 1, example 2, general issue). In this cases it is better to replace those libraries with ones from Nix.

Let's say, that nanomsg library fails to install in virtualenv. Then write a shell.nix file:

let
  pkgs = import <nixpkgs> {};
  nanomsg-py = ...build expression for this python library...;
in pkgs.mkShell {
  buildInputs = [
    pkgs.python3
    pkgs.python3.pkgs.requests
    nanomsg-py
  ];
  shellHook = ''
    # Tells pip to put packages into $PIP_PREFIX instead of the usual locations.
    # See https://pip.pypa.io/en/stable/user_guide/#environment-variables.
    export PIP_PREFIX=$(pwd)/_build/pip_packages
    export PYTHONPATH="$PIP_PREFIX/${pkgs.python3.sitePackages}:$PYTHONPATH"
    export PATH="$PIP_PREFIX/bin:$PATH"
    unset SOURCE_DATE_EPOCH
  '';
}

After entering the environment with `nix-shell`, you can install new python libraries with dump `pip install`, but nanomsg will be detected as installed.

Discussion and consequences of this approach are in PR https://github.com/NixOS/nixpkgs/pull/55265.

micromamba

Install the micromamba package. You can create environments and install packages as documented by micromamba e.g.

micromamba create -n my-environment python=3.9 numpy=1.23.0 -c conda-forge

To activate an environment you will need a FHS environment e.g.:

$ nix-shell -E 'with import <nixpkgs> {}; (pkgs.buildFHSUserEnv { name = "fhs"; }).env'
$ eval "$(micromamba shell hook -s bash)"
$ micromamba activate my-environment
$ python
>>> import numpy as np

Eventually you'll probably want to put this in a shell.nix so you won't have to type all that stuff every time e.g.:

{ pkgs ? import <nixpkgs> {}}:
let
  fhs = pkgs.buildFHSUserEnv {
    name = "my-fhs-environment";

    targetPkgs = _: [
      pkgs.micromamba
    ];

    profile = ''
      set -e
      eval "$(micromamba shell hook --shell=posix)"
      export MAMBA_ROOT_PREFIX=${builtins.getEnv "PWD"}/.mamba
      micromamba create -q -n my-mamba-environment
      micromamba activate my-mamba-environment
      micromamba install --yes -f conda-requirements.txt -c conda-forge
      set +e
    '';
  };
in fhs.env


conda

Install the package conda and run

conda-shell
conda-install
conda env update --file environment.yml

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

pip2nix

pip2nix generate nix expressions for Python packages.

Also see the pypi2nix-project (abandoned in 2019).

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.

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 {
# ...

Special Modules

GNOME

gobject-introspection based python modules need some environment variables to work correctly. For standalone applications, wrapGAppsHook (see the relevant documentation) wraps the executable with the necessary variables. But this is not fit for development. In this case use a nix-shell with gobject-introspection and all the libraries you are using (gtk and so on) as buildInputs. For example:

$ nix-shell -p gobjectIntrospection gtk3 'python2.withPackages (ps: with ps; [ pygobject3 ])' --run "python -c \"import pygtkcompat; pygtkcompat.enable_gtk(version='3.0')\""

Or, if you want to use matplotlib interactively:

$ nix-shell -p gobject-introspection gtk3 'python36.withPackages(ps : with ps; [ matplotlib pygobject3 ipython ])'
$ ipython
In [1]: import matplotlib
In [2]: matplotlib.use('gtk3agg')
In [3]: import matplotlib.pyplot as plt
In [4]: plt.ion()
In [5]: plt.plot([1,3,2,4])

You can also set backend : GTK3Agg in your ~/.config/matplotlib/matplotlibrc file to avoid having to call matplotlib.use('gtk3agg').

Performance

The derivation of cPython that is available via nixpkgs does not contain optimizations enabled, specifically Profile Guided Optimization (PGO) and Link Time Optimization (LTO). See Configuring Python 3.1.3. Performance options Additionally, when you compile something within nix-shell or a derivation; by default there are security hardening flags passed to the compiler which do have a small performance impact.

As of the time of this writing; these optimizations cause Python builds to be non-reproducible and increase install times for the derivation. For a more detailed overview of the trials and tabulations of discovering the performance regression; see Why is the nix-compiled Python slower? thread on the nix forums.


Regression

With the nixpkgs version of Python you can expect anywhere from a 30-40% regression on synthetic benchmarks. For example:

## Ubuntu's Python 3.8
username:dir$ python3.8 -c "import timeit; print(timeit.Timer('for i in range(100): oct(i)', 'gc.enable()').repeat(5))"
[7.831622750498354, 7.82998560462147, 7.830805554986, 7.823807033710182, 7.84282516874373]

## nix-shell's Python 3.8
[nix-shell:~/src]$ python3.8 -c "import timeit; print(timeit.Timer('for i in range(100): oct(i)', 'gc.enable()').repeat(5))"
[10.431915327906609, 10.435049421153963, 10.449542525224388, 10.440207410603762, 10.431304694153368]

However, synthetic benchmarks are not a reflection of a real-world use case. In most situations, the performance difference between optimized & non-optimized interpreters is minimal. For example; using pylint with a significant number of custom linters to go scan a very large Python codebase (>6000 files) resulted in only a 5.5% difference, instead of 40%. Other workflows that were not performance sensitive saw no impact to their run times.


Possible Optimizations

If you run code that heavily depends on Python performance (data science, machine learning), and you want to have the most performant Python interpreter possible, here are some possible things you can do:

  • Enable the enableOptimizations flag for your Python derivation. Example Do note that this will cause you to compile Python the first time that you run it; which will take a few minutes.
  • Switch to a newer version of Python. In the example above, going from 3.8 to 3.10 yielded an average 7.5% performance improvement; but this is only a single benchmark. Switching versions most likely won't make all your code 7.5% faster.
  • Disable hardening, although this only yields a small performance boost; and it has impacts beyond Python code. Hardening in Nixpkgs

Ultimately, it is up to your use case to determine if you need an optimized version of the Python interpreter. We encourage you to benchmark and test your code to determine if this is something that would benefit you.

Troubleshotting

My module cannot be imported

If you are unable to do `import yourmodule` there are a number of reasons that could explain that.

First, make sure that you installed/added your module to python. Typically you would use something like (python3.withPackages (ps: with ps; [ yourmodule ])) in the list of installed applications.

It is also still possible (e.g. when using nix-shell) that you aren't using the python interpreter you want because another package provides its own python3.withPackages in buildInputs, for example, yosys. In this case, you should either include that package (or all needed packages) in your withPackages list to only have a single Python interpreter. Or you can change the order of your packages, such that the python3.withPackages comes first, and becomes the Python interpreter that you get.

If you packaged yourself your application, make sure to use buildPythonPackage and **not** buildPythonApplication or stdenv.mkDerivation. The reason is that python3.withPackages filters the packages to check that they are built using the appropriate python interpreter: this is done by verifying that the derivation has a pythonModule attribute and only buildPythonPackage sets this value (passthru here) thanks to, notably passthru = { pythonModule = python; }. If you used stdenv.mkDerivation then you can maybe set this value manually, but it's safer to simply use buildPythonPackage {format = "other"; … your derivation …} instead of mkDerivation.

See also