or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# Cython

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: Cython

7

- **Language**: Python

8

- **Installation**: `pip install Cython`

9

- **Documentation**: https://cython.readthedocs.io/

10

- **Repository**: https://github.com/cython/cython

11

12

## Core Imports

13

14

```python

15

import cython

16

```

17

18

For the build system:

19

20

```python

21

from Cython.Build import cythonize

22

```

23

24

For import hooks:

25

26

```python

27

import pyximport

28

pyximport.install()

29

```

30

31

For distutils integration:

32

33

```python

34

from Cython.Distutils import build_ext, Extension

35

```

36

37

## Basic Usage

38

39

### Simple Cython Code with Type Annotations

40

41

```python

42

import cython

43

44

@cython.cfunc

45

@cython.locals(x=cython.int, y=cython.int)

46

def add_numbers(x, y):

47

return x + y

48

49

# Using Cython types with declare

50

def fibonacci(n):

51

n_typed = cython.declare(cython.int, n)

52

if n_typed <= 1:

53

return n_typed

54

return fibonacci(n_typed-1) + fibonacci(n_typed-2)

55

```

56

57

### Building Extensions with cythonize

58

59

```python

60

from setuptools import setup

61

from Cython.Build import cythonize

62

63

setup(

64

ext_modules = cythonize("my_module.pyx")

65

)

66

```

67

68

### Using Import Hooks

69

70

```python

71

import pyximport

72

pyximport.install()

73

74

# Now you can import .pyx files directly

75

import my_cython_module

76

```

77

78

## Architecture

79

80

Cython operates through a multi-stage compilation process:

81

82

- **Parser**: Converts Cython code (.pyx) into an Abstract Syntax Tree

83

- **Compiler**: Transforms the AST into optimized C/C++ code

84

- **Builder**: Compiles the generated C/C++ code into Python extension modules

85

- **Runtime**: Provides runtime support for Cython features and Python interoperability

86

87

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.

88

89

## Capabilities

90

91

### Core Language Features

92

93

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.

94

95

```python { .api }

96

# Type declarations

97

def declare(t=None, value=_Unspecified, **kwds): ...

98

def cast(t, *args, **kwargs): ...

99

def sizeof(arg): ...

100

def typeof(arg): ...

101

102

# Decorators

103

def locals(**arg_types): ...

104

def cfunc(f): ...

105

def ccall(f): ...

106

def inline(f, *args, **kwds): ...

107

108

# Compiler directives

109

def boundscheck(flag): ...

110

def wraparound(flag): ...

111

def cdivision(flag): ...

112

```

113

114

[Core Language](./core-language.md)

115

116

### Build System

117

118

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

119

120

```python { .api }

121

def cythonize(module_list, exclude=None, nthreads=0, aliases=None,

122

quiet=False, force=None, language=None,

123

exclude_failures=False, show_all_warnings=False, **options): ...

124

```

125

126

[Build System](./build-system.md)

127

128

### Import System

129

130

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.

131

132

```python { .api }

133

def install(pyximport=True, pyimport=False, build_dir=None,

134

build_in_temp=True, setup_args=None, reload_support=False,

135

load_py_module_on_import_failure=False, inplace=False,

136

language_level=None): ...

137

def uninstall(py_importer, pyx_importer): ...

138

```

139

140

[Import System](./import-system.md)

141

142

### Command Line Tools

143

144

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

145

146

```bash { .api }

147

cython [options] sourcefile.pyx

148

cythonize [options] sourcefile.pyx

149

cygdb [options] [path-to-project-directory]

150

```

151

152

[Command Line Tools](./command-line-tools.md)

153

154

### IPython/Jupyter Integration

155

156

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

157

158

```python { .api }

159

def load_ipython_extension(ip): ...

160

161

%%cython [options]

162

%%cython_inline

163

%%cython_pyximport module_name

164

```

165

166

[IPython/Jupyter Integration](./ipython-integration.md)

167

168

### Debugging and Profiling

169

170

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

171

172

```bash { .api }

173

cygdb [options] [path-to-project-directory] [gdb-args...]

174

```

175

176

```python { .api }

177

@cython.profile(True)

178

@cython.linetrace(True)

179

def profiled_function(): ...

180

```

181

182

[Debugging and Profiling](./debugging-profiling.md)

183

184

### C/C++ Interoperability

185

186

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

187

188

```python { .api }

189

# Standard library bindings

190

from cpython.object cimport PyObject, Py_INCREF, Py_DECREF

191

from libc.stdlib cimport malloc, free

192

from libcpp.vector cimport vector

193

from posix.unistd cimport getpid

194

195

# External library declaration

196

cdef extern from "library.h":

197

int external_function(int arg)

198

```

199

200

[C/C++ Interoperability](./c-cpp-interoperability.md)

201

202

### Compiler Interface

203

204

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

205

206

```python { .api }

207

def compile(source, options=None, full_module_name=None, **kwds):

208

"""Compile Cython source code to C/C++ extensions.

209

210

Args:

211

source: Source code string or sequence of source files

212

options: CompilationOptions instance

213

full_module_name: Full module name for compilation

214

**kwds: Additional compilation options

215

216

Returns:

217

CompilationResult or CompilationResultSet

218

"""

219

220

def compile_single(source, options, full_module_name, cache=None):

221

"""Compile a single source file."""

222

223

def compile_multiple(sources, options, cache=None):

224

"""Compile multiple source files with dependency tracking."""

225

```

226

227

## Types

228

229

### Core Types

230

231

```python { .api }

232

# Fundamental types

233

class typedef:

234

def __init__(self, type, name=None): ...

235

def __call__(self, *arg): ...

236

237

# Primitive types (available as module attributes)

238

int = typedef(int, "int")

239

long = typedef(int, "long")

240

float = typedef(float, "float")

241

double = typedef(float, "double")

242

char = typedef(int, "char")

243

bint = typedef(bool, "bint")

244

void = typedef(None, "void")

245

246

# Pointer and array types

247

def pointer(basetype): ...

248

def array(basetype, n): ...

249

250

# Structure types

251

def struct(**members): ...

252

def union(**members): ...

253

254

# Type modifiers

255

class const:

256

def __class_getitem__(cls, base_type): ...

257

258

class volatile:

259

def __class_getitem__(cls, base_type): ...

260

```

261

262

### Fused Types

263

264

```python { .api }

265

def fused_type(*args): ...

266

267

# Pre-defined fused types

268

integral: _FusedType

269

floating: _FusedType

270

numeric: _FusedType

271

```

272

273

### Parallel Computing Types

274

275

```python { .api }

276

class CythonDotParallel:

277

"""The cython.parallel module for parallel computing."""

278

279

def parallel(self, num_threads=None):

280

"""Context manager for parallel regions.

281

282

Args:

283

num_threads: Number of threads to use (default: system maximum)

284

285

Returns:

286

Context manager for parallel execution

287

"""

288

289

def prange(self, start=0, stop=None, step=1, nogil=False,

290

schedule=None, chunksize=None, num_threads=None):

291

"""Parallel range loop with OpenMP support.

292

293

Args:

294

start: Loop start value (default: 0)

295

stop: Loop end value (required if start is provided)

296

step: Loop step size (default: 1)

297

nogil: Execute without GIL (default: False)

298

schedule: OpenMP scheduling policy ('static', 'dynamic', 'guided')

299

chunksize: Chunk size for scheduling

300

num_threads: Number of threads to use

301

302

Returns:

303

Range iterator for parallel execution

304

"""

305

306

def threadid(self):

307

"""Get current thread ID in parallel region.

308

309

Returns:

310

Integer thread ID (0-based)

311

"""

312

```

313

314

### Threading and Synchronization Types

315

316

```python { .api }

317

class critical_section:

318

"""Context manager and decorator for thread-safe critical sections."""

319

320

def __init__(self, arg0, arg1=None):

321

"""Initialize critical section with lock objects."""

322

323

def __call__(self, *args, **kwargs):

324

"""Use as decorator for functions."""

325

326

def __enter__(self):

327

"""Enter critical section context."""

328

329

def __exit__(self, exc_class, exc, tb):

330

"""Exit critical section context."""

331

332

class pymutex:

333

"""Python threading mutex implementation."""

334

335

def __init__(self):

336

"""Initialize mutex using threading.Lock."""

337

338

def acquire(self):

339

"""Acquire the mutex lock."""

340

341

def release(self):

342

"""Release the mutex lock."""

343

344

def __enter__(self):

345

"""Context manager entry."""

346

347

def __exit__(self, exc_type, exc_value, traceback):

348

"""Context manager exit."""

349

350

pythread_type_lock = pymutex # Alias for pymutex

351

```

352

353

### Inline Compilation Functions

354

355

```python { .api }

356

def inline(f, *args, **kwargs):

357

"""Inline compile Cython code or mark function for inlining.

358

359

Args:

360

f: Function to inline or C code string

361

*args: Additional arguments for inline compilation

362

**kwargs: Keyword arguments for compilation options

363

364

Returns:

365

Compiled inline function or result

366

"""

367

368

def compile(f):

369

"""Runtime compile a function with Cython.

370

371

Args:

372

f: Function to compile at runtime

373

374

Returns:

375

RuntimeCompiledFunction instance

376

"""

377

```