CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cython

Python compiler that transforms Python code into C/C++ extensions for high-performance computing.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

ipython-integration.mddocs/

IPython/Jupyter Integration

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.

Capabilities

Loading the Extension

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
    """

Cell Magic Commands

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 module

CythonMagics Class

The 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
        """

Usage Examples

Basic Cython Cell Magic

# 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))

Annotated Output for Performance Analysis

%%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

Inline Cython for Quick Calculations

# Define variables in Python
a = 10
b = 20
%%cython_inline
return a * b + 5

Creating Importable Modules

%%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()

Advanced Compilation Options

%%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

NumPy Integration

%%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)

Profile-Guided Optimization

%%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

Debugging with Line Tracing

%%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

Reloading and Caching

# 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

Integration with Existing Python Variables

# 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}")

Error Handling and Debugging

%%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

docs

build-system.md

c-cpp-interoperability.md

command-line-tools.md

core-language.md

debugging-profiling.md

import-system.md

index.md

ipython-integration.md

tile.json