From 1c5f8f16060311029da27e28cd8328b7843e4e78 Mon Sep 17 00:00:00 2001 From: Lauri Niemi Date: Wed, 25 Nov 2026 10:28:40 +0200 Subject: [PATCH 1/5] Whitespace fixes --- content/cython.rst | 52 +++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/content/cython.rst b/content/cython.rst index b9def46e..93437f48 100644 --- a/content/cython.rst +++ b/content/cython.rst @@ -13,7 +13,7 @@ Extending Python with Cython .. objectives:: - - Understand how compiled extension modules can speed up code execution. + - Understand how compiled extension modules can speed up code execution. - Build your first compiled extension module with Cython. - Learn to optimize your Cython code with static type declarations. - Learn to use Numpy arrays in Cython code and implement common performance @@ -47,11 +47,11 @@ runtime by the Python interpreter. The interpreter does a lot of significant overhead. For example, when just adding two integers .. code:: python - + a = 7 b = 6 c = a + b - + the Python interpreter needs to: 1. Check the types of both operands @@ -107,7 +107,7 @@ of C. Cython also makes it easy to interact with external C/C++ code. The Cython compiler processes code written in Python, or more commonly the Cython extension of Python language, and turns it into valid C-code which is then compiled into a Python extension module using a -C compiler (GCC, Clang, MSVC, ...). The Cython programming language is a +C compiler (GCC, Clang, MSVC, ...). The Cython programming language is a superset of Python that adds C-like static type declarations and other features that make it possible to generate efficient machine code. @@ -293,21 +293,21 @@ With Cython we can bypass both restrictions and write efficient loops over Numpy arrays. Consider e.g. a double loop that sets values of a 2D array: .. code:: python - + import numpy as np def slow_looper(N): - """""" - data = np.empty((N, N), dtype=int) - - counter = 0 - for i in range(N): - for j in range(N): + """""" + data = np.empty((N, N), dtype=int) + + counter = 0 + for i in range(N): + for j in range(N): data[i, j] = counter - counter += 1 + counter += 1 -We can Cythonize this as before to optimize the ``for``-loops. A quick check +We can Cythonize this as before to optimize the ``for``-loops. A quick check with ``timeit`` shows that with ``N=100``, the pure Python version takes 820μs and the Cythonized version (without any static typing) takes 700μs. This is nice, but we are still bottlenecked by array lookups and assignments, i.e. the @@ -320,21 +320,21 @@ Cython-specific ``cimport`` keyword, then use Cython's Numpy interface to declare the array's datatype and dimensions: .. code:: python - + import numpy as np # Normal Numpy import cimport numpy as cnp # Import for Numpy C-API def fast_looper(int N): - """""" - - # Type declaration: 2D array of 32-bit integers - cdef cnp.ndarray[cnp.int32_t, ndim=2] data - data = np.empty((N, N), dtype=np.int32) - - cdef int counter = 0 - # double loop is done at nearly C speed - for i in range(N): - for j in range(N): + """""" + + # Type declaration: 2D array of 32-bit integers + cdef cnp.ndarray[cnp.int32_t, ndim=2] data + data = np.empty((N, N), dtype=np.int32) + + cdef int counter = 0 + # double loop is done at nearly C speed + for i in range(N): + for j in range(N): data[i, j] = counter counter += 1 @@ -377,7 +377,7 @@ extra performance: @cython.boundscheck(False) @cython.wraparound(False) def fast_looper(int N): - # ... Same function body as above ... + # ... Same function body as above ... Whether these decorators *actually* result in faster code or not depends on @@ -403,7 +403,7 @@ Here are some rules of thumb to keep in mind when optimizing your code with Cython (see also `Cython docs `__): - Only Cythonize the modules/functions for which performance is *really* - needed. Profiling tools help at identifying such bottlenecks. + needed. Profiling tools help at identifying such bottlenecks. - Static type declarations work the best for fundamental data types (integers, floats, strings) and for contiguous arrays. Operations on heterogeneous lists and dictionaries do not usually benefit much from Cython. From e06c308e3c975a17d176f43cc3a3b4e658107a84 Mon Sep 17 00:00:00 2001 From: Lauri Niemi Date: Wed, 25 Nov 2026 10:32:38 +0200 Subject: [PATCH 2/5] added instructions for getting nbclassic --- content/cython.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/content/cython.rst b/content/cython.rst index 93437f48..af236a99 100644 --- a/content/cython.rst +++ b/content/cython.rst @@ -182,7 +182,12 @@ Using Cython with Jupyter .. important:: Due to a `known issue`_ with ``%%cython -a`` in ``jupyter-lab`` we have to use the ``jupyter-nbclassic`` interface - for this episode. + for this episode. Install and launch it with: + + .. code:: bash + + pip install nbclassic + jupyter nbclassic .. _known issue: https://github.com/cython/cython/issues/7319 From 2a1c1cca9be7f01268d4a44fb8720f726ae23cdd Mon Sep 17 00:00:00 2001 From: Lauri Niemi Date: Wed, 25 Nov 2026 11:09:56 +0200 Subject: [PATCH 3/5] Use Cython memoryviews for numpy arrays instead of direct array syntax --- content/cython.rst | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/content/cython.rst b/content/cython.rst index af236a99..ad805511 100644 --- a/content/cython.rst +++ b/content/cython.rst @@ -303,7 +303,7 @@ Numpy arrays. Consider e.g. a double loop that sets values of a 2D array: def slow_looper(N): """""" - data = np.empty((N, N), dtype=int) + data = np.empty((N, N), dtype=np.int32) counter = 0 for i in range(N): @@ -319,28 +319,29 @@ nice, but we are still bottlenecked by array lookups and assignments, i.e. the ``[]`` operator, which invokes Python code. We can get a huge speedup by adding a static type declaration for the Numpy -array, and for the other variables too while we are at it. To do this we must -import compile-time information about the Numpy module using the -Cython-specific ``cimport`` keyword, then use Cython's Numpy interface to -declare the array's datatype and dimensions: +array. The recommended way of doing this is with a **typed memoryview**: a +Cython type that describes a block of memory with given element type and shape. +In the following we use a 2D memoryview for writing to the array-owned memory, +which lets Cython optimize the memory accesses. We've also added static type +declarations for the integer variables. .. code:: python - import numpy as np # Normal Numpy import - cimport numpy as cnp # Import for Numpy C-API + import numpy as np def fast_looper(int N): """""" - - # Type declaration: 2D array of 32-bit integers - cdef cnp.ndarray[cnp.int32_t, ndim=2] data data = np.empty((N, N), dtype=np.int32) + # Create a 2D Cython view into the array. Cheap operation. + cdef int[:, :] data_view = data + cdef int counter = 0 # double loop is done at nearly C speed for i in range(N): for j in range(N): - data[i, j] = counter + # Modify the array via the Cython memory view + data_view[i, j] = counter counter += 1 @@ -350,18 +351,13 @@ pure Python implementation! .. callout:: - ``cimport numpy`` needs access to Numpy C-headers which are usually included - in Python distributions. This usually works out of the box for Jupyter - notebooks. However, if using the command line ``cythonize`` tool you may need - to manually set include paths for the C compiler. - Refer to `the docs `__ - for more details. - -.. callout:: + Memoryviews are not specific to Numpy: any Python object that exposes the + `buffer protocol `__ (e.g. + Python's built-in ``array`` module, or other array libraries) can be + assigned to a memoryview, using the same syntax as above. - It is good practice to also call ``cnp.import_array()`` after doing the - ``cimport`` of Numpy. This is required for accessing attributes (like - ``.shape``) of typed Numpy arrays. + Cython also has a `Numpy-specific array syntax `__ + that you may see used especially in older code. More Numpy indexing enhancements @@ -376,7 +372,6 @@ extra performance: .. code:: python import numpy as np - cimport numpy as cnp cimport cython @cython.boundscheck(False) @@ -433,8 +428,6 @@ to use it from Python, consider using one of the following: Further reading --------------- -- Cython `memory views `__ - are a newer and more general way of interfacing with Numpy arrays and other buffer-like objects. - `Calling C functions from Cython `__ From 1caabb6ebeb157c7b9a847772ae66d4db3b58e23 Mon Sep 17 00:00:00 2001 From: Lauri Niemi Date: Wed, 25 Nov 2026 11:12:36 +0200 Subject: [PATCH 4/5] Mention nanobind as a newer alternative to pybind11 --- content/cython.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/content/cython.rst b/content/cython.rst index ad805511..707c51fe 100644 --- a/content/cython.rst +++ b/content/cython.rst @@ -423,6 +423,7 @@ to use it from Python, consider using one of the following: - `ctypes `__: part of Python standard library. - `CFFI `__: somewhat similar to `ctypes` but with more features and probably better for large projects. - `pybind11 `__: very robust and modern way of creating extension modules. C++ only. + See also its newer cousin `nanobind `__. - `PyO3 `__ for Rust code. Further reading From c09821a8de0124767e8bd6e81729587975d0dcac Mon Sep 17 00:00:00 2001 From: Lauri Niemi Date: Wed, 25 Nov 2026 11:16:21 +0200 Subject: [PATCH 5/5] Clarify array access --- content/cython.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/content/cython.rst b/content/cython.rst index 707c51fe..0a94261c 100644 --- a/content/cython.rst +++ b/content/cython.rst @@ -318,9 +318,9 @@ and the Cythonized version (without any static typing) takes 700μs. This is nice, but we are still bottlenecked by array lookups and assignments, i.e. the ``[]`` operator, which invokes Python code. -We can get a huge speedup by adding a static type declaration for the Numpy -array. The recommended way of doing this is with a **typed memoryview**: a -Cython type that describes a block of memory with given element type and shape. +We can get a huge speedup by Cythonizing the array access. +The recommended way of doing this is with a **typed memoryview**: a Cython type +that describes a block of memory with given element type and shape. In the following we use a 2D memoryview for writing to the array-owned memory, which lets Cython optimize the memory accesses. We've also added static type declarations for the integer variables.