0
# Core Language Features
1
2
Cython's core language constructs, type system, decorators, and compiler directives that extend Python with static typing and C-level performance. These features enable seamless integration between Python and C code while maintaining Python's syntax and readability.
3
4
## Capabilities
5
6
### Type System and Declarations
7
8
Core functions for declaring variables with C types, casting between types, and introspecting type information.
9
10
```python { .api }
11
def declare(t=None, value=_Unspecified, **kwds):
12
"""Declare a variable with a specific Cython type.
13
14
Args:
15
t: The type to declare (int, double, etc.)
16
value: Optional initial value
17
**kwds: Additional type parameters
18
19
Returns:
20
The declared variable with proper type
21
"""
22
23
def cast(t, *args, **kwargs):
24
"""Cast a value to a specific type.
25
26
Args:
27
t: Target type for casting
28
*args: Values to cast
29
**kwargs: Additional casting options (typecheck, etc.)
30
31
Returns:
32
The value cast to the target type
33
"""
34
35
def sizeof(arg):
36
"""Get the size in bytes of a type or object.
37
38
Args:
39
arg: Type or object to measure
40
41
Returns:
42
Size in bytes (returns 1 in pure Python mode)
43
"""
44
45
def typeof(arg):
46
"""Get the type name of an object.
47
48
Args:
49
arg: Object to inspect
50
51
Returns:
52
String representation of the object's type
53
"""
54
55
def address(arg):
56
"""Get the memory address of an object as a pointer.
57
58
Args:
59
arg: Object to get address of
60
61
Returns:
62
Pointer to the object
63
"""
64
```
65
66
### Function Decorators
67
68
Decorators that modify function behavior for performance and C integration.
69
70
```python { .api }
71
def locals(**arg_types):
72
"""Declare local variable types for a function.
73
74
Args:
75
**arg_types: Mapping of variable names to types
76
77
Returns:
78
Decorator function
79
"""
80
81
def cfunc(f):
82
"""Mark a function as a C function (cdef).
83
84
Args:
85
f: Function to mark as C function
86
87
Returns:
88
The function marked for C compilation
89
"""
90
91
def ccall(f):
92
"""Mark a function as callable from C code.
93
94
Args:
95
f: Function to mark as C callable
96
97
Returns:
98
The function marked as C callable
99
"""
100
101
def inline(f, *args, **kwds):
102
"""Inline C code or mark function for inlining.
103
104
Args:
105
f: Function to inline or C code string
106
*args: Additional arguments for inline compilation
107
**kwds: Keyword arguments for compilation
108
109
Returns:
110
Inlined function or compiled inline code result
111
"""
112
113
def compile(f):
114
"""Runtime compile a function with Cython.
115
116
Args:
117
f: Function to compile at runtime
118
119
Returns:
120
RuntimeCompiledFunction instance
121
"""
122
```
123
124
### Compiler Directives
125
126
Directives that control Cython compiler behavior and optimizations.
127
128
```python { .api }
129
def boundscheck(flag):
130
"""Control array bounds checking.
131
132
Args:
133
flag: Boolean to enable/disable bounds checking
134
135
Returns:
136
Decorator/context manager for bounds checking control
137
"""
138
139
def wraparound(flag):
140
"""Control negative array indexing.
141
142
Args:
143
flag: Boolean to enable/disable wraparound indexing
144
145
Returns:
146
Decorator/context manager for wraparound control
147
"""
148
149
def cdivision(flag):
150
"""Use C division semantics instead of Python division.
151
152
Args:
153
flag: Boolean to enable/disable C division
154
155
Returns:
156
Decorator/context manager for division control
157
"""
158
159
def profile(flag):
160
"""Enable profiling support for functions.
161
162
Args:
163
flag: Boolean to enable/disable profiling
164
165
Returns:
166
Decorator for profiling control
167
"""
168
169
def linetrace(flag):
170
"""Enable line tracing for debugging.
171
172
Args:
173
flag: Boolean to enable/disable line tracing
174
175
Returns:
176
Decorator for line tracing control
177
"""
178
179
def exceptval(value=None, check=True):
180
"""Set exception return value for C functions.
181
182
Args:
183
value: Value to return on exception
184
check: Whether to check for exceptions
185
186
Returns:
187
Decorator for exception handling control
188
"""
189
```
190
191
### GIL Control
192
193
Context managers and decorators for controlling Python's Global Interpreter Lock.
194
195
```python { .api }
196
class _nogil:
197
"""Context manager and decorator for releasing the GIL."""
198
199
def __call__(self, x):
200
"""Use as decorator to mark function as nogil.
201
202
Args:
203
x: Function to mark as nogil
204
205
Returns:
206
The function marked for nogil execution
207
"""
208
209
def __enter__(self):
210
"""Enter nogil context."""
211
212
def __exit__(self, exc_class, exc, tb):
213
"""Exit nogil context.
214
215
Returns:
216
True if no exception occurred
217
"""
218
219
nogil = _nogil()
220
gil = _nogil() # Re-acquire GIL context manager
221
with_gil = _nogil() # Decorator ensuring function runs with GIL
222
```
223
224
### Memory Operations
225
226
Functions for low-level memory operations and C-style arithmetic.
227
228
```python { .api }
229
def cdiv(a, b):
230
"""Perform C-style integer division.
231
232
Args:
233
a: Dividend
234
b: Divisor
235
236
Returns:
237
Result of C-style division
238
"""
239
240
def cmod(a, b):
241
"""Perform C-style modulo operation.
242
243
Args:
244
a: Dividend
245
b: Divisor
246
247
Returns:
248
Result of C-style modulo
249
"""
250
```
251
252
### Threading Support
253
254
Classes for thread synchronization and critical sections.
255
256
```python { .api }
257
class critical_section:
258
"""Context manager and decorator for thread-safe critical sections."""
259
260
def __init__(self, arg0, arg1=None):
261
"""Initialize critical section.
262
263
Args:
264
arg0: Lock object or function to protect
265
arg1: Optional second lock object
266
"""
267
268
def __call__(self, *args, **kwds):
269
"""Use as decorator."""
270
271
def __enter__(self):
272
"""Enter critical section."""
273
274
def __exit__(self, exc_class, exc, tb):
275
"""Exit critical section."""
276
277
class pymutex:
278
"""Python threading mutex implementation."""
279
280
def __init__(self):
281
"""Initialize mutex using threading.Lock."""
282
283
def acquire(self):
284
"""Acquire the mutex lock."""
285
286
def release(self):
287
"""Release the mutex lock."""
288
289
def __enter__(self):
290
"""Context manager entry."""
291
292
def __exit__(self, exc_type, exc_value, traceback):
293
"""Context manager exit."""
294
295
pythread_type_lock = pymutex # Alias for pymutex
296
```
297
298
## Usage Examples
299
300
### Basic Type Declarations
301
302
```python
303
import cython
304
305
# Declare variables with specific types
306
x = cython.declare(cython.int, 5)
307
y = cython.declare(cython.double, 3.14)
308
309
# Cast between types
310
result = cython.cast(cython.long, x * y)
311
312
# Get type information
313
print(cython.typeof(result)) # Prints type name
314
print(cython.sizeof(cython.int)) # Prints size in bytes
315
```
316
317
### Function Optimization
318
319
```python
320
import cython
321
322
@cython.cfunc
323
@cython.locals(x=cython.int, y=cython.int)
324
def fast_add(x, y):
325
return x + y
326
327
@cython.boundscheck(False)
328
@cython.wraparound(False)
329
def fast_array_sum(arr):
330
total = 0
331
for i in range(len(arr)):
332
total += arr[i]
333
return total
334
```
335
336
### GIL Management
337
338
```python
339
import cython
340
341
@cython.nogil
342
def cpu_intensive_task():
343
# This function releases the GIL
344
result = 0
345
for i in range(1000000):
346
result += i * i
347
return result
348
349
def mixed_function():
350
with cython.nogil:
351
# CPU-intensive work without GIL
352
result = cpu_intensive_task()
353
354
# Python operations with GIL
355
print(f"Result: {result}")
356
```