Pythran
Pythran is an Ahead-of-Time (AOT) compiler that translates a subset of Python, primarily focused on scientific computing and numerical kernels, into native C++14 modules. It aims to provide C++/Fortran-like performance for Python code, leveraging multi-cores and SIMD instructions. The current stable version is 0.18.1, and it actively maintains a release cadence of several updates per year, supporting Python 3.7 and upward.
Warnings
- breaking Pythran dropped support for Python 2.7 after version 0.9.5. It now exclusively supports Python 3.7 and upward.
- gotcha Pythran only supports a subset of the Python language, specifically targeting numerical computing. Features like classes, polymorphic variables (with some exceptions), and heterogeneous containers (except tuples) are not supported.
- gotcha A C++14 enabled compiler (e.g., g++ >= 5, clang >= 3.5) is a prerequisite for Pythran. Older compilers may lead to compilation errors.
- gotcha For optimal performance, users often need to explicitly specify compiler optimization flags (e.g., `-O3`, `-fopenmp`, `-march=native`) either via the `pythran` CLI or in a `~/.pythranrc` configuration file.
- deprecated Support for `numpy.distutils` with Python 3.9 was obsoleted in Pythran 0.18.0. Users integrating Pythran into larger build systems might need to adapt.
- gotcha Windows support for Pythran is ongoing and primarily targets Visual Studio 2017 or clang-cl. Specific environment variables (`CXX`, `CC`) might be required for proper setup.
Install
-
pip install pythran
Imports
- compiled_module
import compiled_module
- pythran.magic
%load_ext pythran.magic
Quickstart
# dprod.py
""" Naive dotproduct! Pythran supports numpy.dot """
#pythran export dprod(int list, int list)
def dprod(l0, l1):
"""WoW, generator expression, zip and sum."""
return sum(x * y for x, y in zip(l0, l1))
# To compile the Python file to a native module:
# pythran dprod.py
# Then, import and use the compiled module:
# python -c 'import dprod; print(dprod.dprod([1,2,3], [4,5,6]))'