or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

build-system.mdc-cpp-interoperability.mdcommand-line-tools.mdcore-language.mddebugging-profiling.mdimport-system.mdindex.mdipython-integration.md
tile.json

tessl/pypi-cython

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cython@3.1.x

To install, run

npx @tessl/cli install tessl/pypi-cython@3.1.0

index.mddocs/

Cython

A Python compiler that transforms Python code into C/C++ extensions, making it as easy to write C extensions as Python itself. Cython provides a superset of the Python language with optional static typing capabilities, enabling developers to achieve significant performance improvements while maintaining Python's ease of use.

Package Information

  • Package Name: Cython
  • Language: Python
  • Installation: pip install Cython
  • Documentation: https://cython.readthedocs.io/
  • Repository: https://github.com/cython/cython

Core Imports

import cython

For the build system:

from Cython.Build import cythonize

For import hooks:

import pyximport
pyximport.install()

For distutils integration:

from Cython.Distutils import build_ext, Extension

Basic Usage

Simple Cython Code with Type Annotations

import cython

@cython.cfunc
@cython.locals(x=cython.int, y=cython.int)
def add_numbers(x, y):
    return x + y

# Using Cython types with declare
def fibonacci(n):
    n_typed = cython.declare(cython.int, n)
    if n_typed <= 1:
        return n_typed
    return fibonacci(n_typed-1) + fibonacci(n_typed-2)

Building Extensions with cythonize

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("my_module.pyx")
)

Using Import Hooks

import pyximport
pyximport.install()

# Now you can import .pyx files directly
import my_cython_module

Architecture

Cython operates through a multi-stage compilation process:

  • Parser: Converts Cython code (.pyx) into an Abstract Syntax Tree
  • Compiler: Transforms the AST into optimized C/C++ code
  • Builder: Compiles the generated C/C++ code into Python extension modules
  • Runtime: Provides runtime support for Cython features and Python interoperability

The core language extensions include static typing for variables, function parameters, and return values, as well as direct C function calls, C data structures, and seamless integration with existing C/C++ libraries.

Capabilities

Core Language Features

Cython's language constructs, type system, decorators, and compiler directives that extend Python with static typing and C-level performance. Includes primitive types, pointer operations, memory management, and GIL control.

# Type declarations
def declare(t=None, value=_Unspecified, **kwds): ...
def cast(t, *args, **kwargs): ...
def sizeof(arg): ...
def typeof(arg): ...

# Decorators
def locals(**arg_types): ...
def cfunc(f): ...
def ccall(f): ...
def inline(f, *args, **kwds): ...

# Compiler directives
def boundscheck(flag): ...
def wraparound(flag): ...
def cdivision(flag): ...

Core Language

Build System

The cythonize function and build infrastructure for converting .pyx files into compiled extension modules. Supports setuptools integration, parallel compilation, and advanced build configuration.

def cythonize(module_list, exclude=None, nthreads=0, aliases=None, 
              quiet=False, force=None, language=None, 
              exclude_failures=False, show_all_warnings=False, **options): ...

Build System

Import System

Import hooks that allow importing .pyx files directly as Python modules without explicit compilation. Provides automatic compilation and caching of Cython modules at import time.

def install(pyximport=True, pyimport=False, build_dir=None, 
            build_in_temp=True, setup_args=None, reload_support=False,
            load_py_module_on_import_failure=False, inplace=False,
            language_level=None): ...
def uninstall(py_importer, pyx_importer): ...

Import System

Command Line Tools

Command line interfaces for compiling Cython code, building extensions, and debugging. Includes the cython compiler, cythonize build tool, and cygdb debugger.

cython [options] sourcefile.pyx
cythonize [options] sourcefile.pyx
cygdb [options] [path-to-project-directory]

Command Line Tools

IPython/Jupyter Integration

Magic commands and extensions for interactive Cython development in IPython and Jupyter notebooks. Enables inline compilation, execution, and debugging of Cython code.

def load_ipython_extension(ip): ...

%%cython [options]
%%cython_inline
%%cython_pyximport module_name

IPython/Jupyter Integration

Debugging and Profiling

Comprehensive debugging and profiling tools for analyzing and optimizing Cython code. Includes source-level debugging, performance analysis, and bottleneck identification.

cygdb [options] [path-to-project-directory] [gdb-args...]
@cython.profile(True)
@cython.linetrace(True)
def profiled_function(): ...

Debugging and Profiling

C/C++ Interoperability

Extensive capabilities for interfacing with C and C++ libraries, including standard library bindings, external library interfaces, and tools for wrapping existing codebases.

# Standard library bindings
from cpython.object cimport PyObject, Py_INCREF, Py_DECREF
from libc.stdlib cimport malloc, free
from libcpp.vector cimport vector
from posix.unistd cimport getpid

# External library declaration
cdef extern from "library.h":
    int external_function(int arg)

C/C++ Interoperability

Compiler Interface

Direct access to Cython's compilation pipeline for advanced use cases and tooling integration.

def compile(source, options=None, full_module_name=None, **kwds):
    """Compile Cython source code to C/C++ extensions.
    
    Args:
        source: Source code string or sequence of source files
        options: CompilationOptions instance
        full_module_name: Full module name for compilation
        **kwds: Additional compilation options
    
    Returns:
        CompilationResult or CompilationResultSet
    """

def compile_single(source, options, full_module_name, cache=None):
    """Compile a single source file."""

def compile_multiple(sources, options, cache=None):
    """Compile multiple source files with dependency tracking."""

Types

Core Types

# Fundamental types
class typedef:
    def __init__(self, type, name=None): ...
    def __call__(self, *arg): ...

# Primitive types (available as module attributes)
int = typedef(int, "int")
long = typedef(int, "long") 
float = typedef(float, "float")
double = typedef(float, "double")
char = typedef(int, "char")
bint = typedef(bool, "bint")
void = typedef(None, "void")

# Pointer and array types
def pointer(basetype): ...
def array(basetype, n): ...

# Structure types
def struct(**members): ...
def union(**members): ...

# Type modifiers
class const:
    def __class_getitem__(cls, base_type): ...

class volatile:
    def __class_getitem__(cls, base_type): ...

Fused Types

def fused_type(*args): ...

# Pre-defined fused types
integral: _FusedType
floating: _FusedType
numeric: _FusedType

Parallel Computing Types

class CythonDotParallel:
    """The cython.parallel module for parallel computing."""
    
    def parallel(self, num_threads=None):
        """Context manager for parallel regions.
        
        Args:
            num_threads: Number of threads to use (default: system maximum)
        
        Returns:
            Context manager for parallel execution
        """
    
    def prange(self, start=0, stop=None, step=1, nogil=False, 
               schedule=None, chunksize=None, num_threads=None):
        """Parallel range loop with OpenMP support.
        
        Args:
            start: Loop start value (default: 0)
            stop: Loop end value (required if start is provided)
            step: Loop step size (default: 1)
            nogil: Execute without GIL (default: False)
            schedule: OpenMP scheduling policy ('static', 'dynamic', 'guided')
            chunksize: Chunk size for scheduling
            num_threads: Number of threads to use
        
        Returns:
            Range iterator for parallel execution
        """
    
    def threadid(self):
        """Get current thread ID in parallel region.
        
        Returns:
            Integer thread ID (0-based)
        """

Threading and Synchronization Types

class critical_section:
    """Context manager and decorator for thread-safe critical sections."""
    
    def __init__(self, arg0, arg1=None):
        """Initialize critical section with lock objects."""
    
    def __call__(self, *args, **kwargs):
        """Use as decorator for functions."""
    
    def __enter__(self):
        """Enter critical section context."""
    
    def __exit__(self, exc_class, exc, tb):
        """Exit critical section context."""

class pymutex:
    """Python threading mutex implementation."""
    
    def __init__(self):
        """Initialize mutex using threading.Lock."""
    
    def acquire(self):
        """Acquire the mutex lock."""
    
    def release(self):
        """Release the mutex lock."""
    
    def __enter__(self):
        """Context manager entry."""
    
    def __exit__(self, exc_type, exc_value, traceback):
        """Context manager exit."""

pythread_type_lock = pymutex  # Alias for pymutex

Inline Compilation Functions

def inline(f, *args, **kwargs):
    """Inline compile Cython code or mark function for inlining.
    
    Args:
        f: Function to inline or C code string
        *args: Additional arguments for inline compilation
        **kwargs: Keyword arguments for compilation options
    
    Returns:
        Compiled inline function or result
    """

def compile(f):
    """Runtime compile a function with Cython.
    
    Args:
        f: Function to compile at runtime
    
    Returns:
        RuntimeCompiledFunction instance
    """