Cython's Core: `def` vs. `cdef` vs. `cpdef` Explained
Cython offers three function declaration types for direct C conversion: `def` for Python-callable functions with Python object overhead; `cdef` for pure C functions, fastest for internal calls within Cython/C but not directly callable from Python; and `cpdef` as a hybrid, providing both a fast C-level call for Cython and a Python-callable wrapper, with dynamic binding overhead for Python objects.
The top 3
- Performance Hierarchy: `cdef` vs. `cpdef` vs. `def`: Comparing `cdef`, `cpdef`, and `def` functions, `cdef` offers the fastest execution as it's pure C-level, followed by `cpdef` which has a slight overhead for its Python wrapper, and `def` being the slowest due to full Python semantics.
- Visibility & API: Who Can Call What?: `def` and `cpdef` functions are callable directly from Python code, making them suitable for public APIs. In contrast, `cdef` functions are strictly C-level and can only be called from other Cython or C code within the same module, optimizing for internal performance.
- C-level Integration: `cdef`'s Unique Advantage: `cdef` functions are crucial for direct, zero-overhead interaction with external C libraries or C data structures within Cython, enabling performance-critical operations that bypass Python's object model entirely.
Sources
Open the full topic