Python compiler that transforms Python code into C/C++ extensions for high-performance computing.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Cython provides seamless integration with IPython and Jupyter notebooks through magic commands that enable inline compilation and execution of Cython code. This integration allows for interactive development, experimentation, and rapid prototyping with Cython.
Enable Cython magic commands in IPython or Jupyter notebooks.
def load_ipython_extension(ip):
"""Load the Cython extension in IPython.
Args:
ip: IPython InteractiveShell instance
"""Magic commands for compiling and executing Cython code in notebook cells.
%%cython [options]
# Cython code here
%%cython_inline
# Inline Cython code that returns a value
%%cython_pyximport module_name
# Cython code that creates an importable moduleThe main magic command handler providing Cython functionality in IPython.
class CythonMagics:
"""IPython magic commands for Cython compilation."""
def __init__(self, shell):
"""Initialize Cython magics.
Args:
shell: IPython InteractiveShell instance
"""
def cython(self, parameter_s, cell):
"""%%cython magic command for compiling Cython code.
Args:
parameter_s: Command line parameters
cell: Cell content with Cython code
Magic Arguments:
-a, --annotate: Generate annotated HTML output
-c COMPILE_ARGS: Extra compile arguments
-l LINK_ARGS: Extra link arguments
-I INCLUDE_DIRS: Include directories
-f, --force: Force recompilation
-+ : Compile as C++ code
-3: Use Python 3 semantics
--cplus: Generate C++ code
--pgo: Use profile-guided optimization
"""
def cython_inline(self, line, cell):
"""%%cython_inline magic for inline Cython compilation.
Args:
line: Command line (unused)
cell: Cython code to compile and execute inline
Returns:
Result of executing the Cython code
"""
def cython_pyximport(self, line, cell):
"""%%cython_pyximport magic for creating importable modules.
Args:
line: Module name to create
cell: Cython code for the module
"""# Load the extension
%load_ext cython%%cython
def fibonacci(int n):
"""Fast Fibonacci calculation using Cython."""
cdef int a = 0
cdef int b = 1
cdef int i
if n <= 1:
return n
for i in range(2, n + 1):
a, b = b, a + b
return b
# Function is now available in the namespace
print(fibonacci(20))%%cython -a
import numpy as np
def sum_array(double[:] arr):
"""Sum array elements with memory view."""
cdef double total = 0.0
cdef int i
for i in range(arr.shape[0]):
total += arr[i]
return total
# Creates annotated HTML showing C interaction efficiency# Define variables in Python
a = 10
b = 20%%cython_inline
return a * b + 5%%cython_pyximport math_utils
def fast_power(double base, int exp):
"""Fast integer power calculation."""
cdef double result = 1.0
cdef int i
for i in range(exp):
result *= base
return result
def factorial(int n):
"""Calculate factorial."""
cdef int result = 1
cdef int i
for i in range(1, n + 1):
result *= i
return result
# Functions are now available as math_utils.fast_power() and math_utils.factorial()%%cython -c=-O3 -c=-march=native --cplus
#include <vector>
#include <algorithm>
from libcpp.vector cimport vector
def sort_vector(vector[int] vec):
"""Sort a C++ vector."""
sort(vec.begin(), vec.end())
return vec%%cython -c=-I/path/to/numpy/headers
import numpy as np
cimport numpy as cnp
def matrix_multiply(cnp.float64_t[:, :] A, cnp.float64_t[:, :] B):
"""Fast matrix multiplication using Cython and NumPy."""
cdef int M = A.shape[0]
cdef int N = A.shape[1]
cdef int P = B.shape[1]
cdef cnp.float64_t[:, :] C = np.zeros((M, P), dtype=np.float64)
cdef int i, j, k
for i in range(M):
for j in range(P):
for k in range(N):
C[i, j] += A[i, k] * B[k, j]
return np.asarray(C)%%cython --pgo
def cpu_intensive_function(int n):
"""Function that benefits from profile-guided optimization."""
cdef int i, result = 0
for i in range(n):
result += i * i * i
return result
# First run collects profiling data
# Subsequent runs use optimized code based on profiling%%cython -X linetrace=True -X binding=True
def traced_function(int x):
"""Function with line tracing enabled for debugging."""
cdef int y = x * 2
cdef int z = y + 10
return z * z
# Can be profiled and debugged with Python tools# Force recompilation even if source hasn't changed
%%cython -f
def updated_function():
return "New implementation"
# Cython magic automatically caches compiled extensions
# Only recompiles when source code changes# Define data in Python
import numpy as np
data = np.random.random(1000000)
threshold = 0.5%%cython
import numpy as np
def count_above_threshold(double[:] arr, double thresh):
"""Count elements above threshold."""
cdef int count = 0
cdef int i
for i in range(arr.shape[0]):
if arr[i] > thresh:
count += 1
return count
# Use Python variables directly
result = count_above_threshold(data, threshold)
print(f"Found {result} elements above {threshold}")%%cython
def division_function(int a, int b):
"""Function that demonstrates error handling."""
if b == 0:
raise ValueError("Division by zero!")
return a / b
try:
result = division_function(10, 0)
except ValueError as e:
print(f"Error: {e}")The IPython/Jupyter integration makes Cython development highly interactive and accessible, allowing seamless mixing of Python and Cython code with immediate compilation and execution feedback.
Install with Tessl CLI
npx tessl i tessl/pypi-cython