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

ipython-integration.mddocs/

0

# IPython/Jupyter Integration

1

2

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.

3

4

## Capabilities

5

6

### Loading the Extension

7

8

Enable Cython magic commands in IPython or Jupyter notebooks.

9

10

```python { .api }

11

def load_ipython_extension(ip):

12

"""Load the Cython extension in IPython.

13

14

Args:

15

ip: IPython InteractiveShell instance

16

"""

17

```

18

19

### Cell Magic Commands

20

21

Magic commands for compiling and executing Cython code in notebook cells.

22

23

```python { .api }

24

%%cython [options]

25

# Cython code here

26

27

%%cython_inline

28

# Inline Cython code that returns a value

29

30

%%cython_pyximport module_name

31

# Cython code that creates an importable module

32

```

33

34

### CythonMagics Class

35

36

The main magic command handler providing Cython functionality in IPython.

37

38

```python { .api }

39

class CythonMagics:

40

"""IPython magic commands for Cython compilation."""

41

42

def __init__(self, shell):

43

"""Initialize Cython magics.

44

45

Args:

46

shell: IPython InteractiveShell instance

47

"""

48

49

def cython(self, parameter_s, cell):

50

"""%%cython magic command for compiling Cython code.

51

52

Args:

53

parameter_s: Command line parameters

54

cell: Cell content with Cython code

55

56

Magic Arguments:

57

-a, --annotate: Generate annotated HTML output

58

-c COMPILE_ARGS: Extra compile arguments

59

-l LINK_ARGS: Extra link arguments

60

-I INCLUDE_DIRS: Include directories

61

-f, --force: Force recompilation

62

-+ : Compile as C++ code

63

-3: Use Python 3 semantics

64

--cplus: Generate C++ code

65

--pgo: Use profile-guided optimization

66

"""

67

68

def cython_inline(self, line, cell):

69

"""%%cython_inline magic for inline Cython compilation.

70

71

Args:

72

line: Command line (unused)

73

cell: Cython code to compile and execute inline

74

75

Returns:

76

Result of executing the Cython code

77

"""

78

79

def cython_pyximport(self, line, cell):

80

"""%%cython_pyximport magic for creating importable modules.

81

82

Args:

83

line: Module name to create

84

cell: Cython code for the module

85

"""

86

```

87

88

## Usage Examples

89

90

### Basic Cython Cell Magic

91

92

```python

93

# Load the extension

94

%load_ext cython

95

```

96

97

```cython

98

%%cython

99

def fibonacci(int n):

100

"""Fast Fibonacci calculation using Cython."""

101

cdef int a = 0

102

cdef int b = 1

103

cdef int i

104

105

if n <= 1:

106

return n

107

108

for i in range(2, n + 1):

109

a, b = b, a + b

110

111

return b

112

113

# Function is now available in the namespace

114

print(fibonacci(20))

115

```

116

117

### Annotated Output for Performance Analysis

118

119

```cython

120

%%cython -a

121

import numpy as np

122

123

def sum_array(double[:] arr):

124

"""Sum array elements with memory view."""

125

cdef double total = 0.0

126

cdef int i

127

128

for i in range(arr.shape[0]):

129

total += arr[i]

130

131

return total

132

133

# Creates annotated HTML showing C interaction efficiency

134

```

135

136

### Inline Cython for Quick Calculations

137

138

```python

139

# Define variables in Python

140

a = 10

141

b = 20

142

```

143

144

```cython

145

%%cython_inline

146

return a * b + 5

147

```

148

149

### Creating Importable Modules

150

151

```cython

152

%%cython_pyximport math_utils

153

def fast_power(double base, int exp):

154

"""Fast integer power calculation."""

155

cdef double result = 1.0

156

cdef int i

157

158

for i in range(exp):

159

result *= base

160

161

return result

162

163

def factorial(int n):

164

"""Calculate factorial."""

165

cdef int result = 1

166

cdef int i

167

168

for i in range(1, n + 1):

169

result *= i

170

171

return result

172

173

# Functions are now available as math_utils.fast_power() and math_utils.factorial()

174

```

175

176

### Advanced Compilation Options

177

178

```cython

179

%%cython -c=-O3 -c=-march=native --cplus

180

#include <vector>

181

#include <algorithm>

182

183

from libcpp.vector cimport vector

184

185

def sort_vector(vector[int] vec):

186

"""Sort a C++ vector."""

187

sort(vec.begin(), vec.end())

188

return vec

189

```

190

191

### NumPy Integration

192

193

```cython

194

%%cython -c=-I/path/to/numpy/headers

195

import numpy as np

196

cimport numpy as cnp

197

198

def matrix_multiply(cnp.float64_t[:, :] A, cnp.float64_t[:, :] B):

199

"""Fast matrix multiplication using Cython and NumPy."""

200

cdef int M = A.shape[0]

201

cdef int N = A.shape[1]

202

cdef int P = B.shape[1]

203

204

cdef cnp.float64_t[:, :] C = np.zeros((M, P), dtype=np.float64)

205

206

cdef int i, j, k

207

for i in range(M):

208

for j in range(P):

209

for k in range(N):

210

C[i, j] += A[i, k] * B[k, j]

211

212

return np.asarray(C)

213

```

214

215

### Profile-Guided Optimization

216

217

```cython

218

%%cython --pgo

219

def cpu_intensive_function(int n):

220

"""Function that benefits from profile-guided optimization."""

221

cdef int i, result = 0

222

223

for i in range(n):

224

result += i * i * i

225

226

return result

227

228

# First run collects profiling data

229

# Subsequent runs use optimized code based on profiling

230

```

231

232

### Debugging with Line Tracing

233

234

```cython

235

%%cython -X linetrace=True -X binding=True

236

def traced_function(int x):

237

"""Function with line tracing enabled for debugging."""

238

cdef int y = x * 2

239

cdef int z = y + 10

240

return z * z

241

242

# Can be profiled and debugged with Python tools

243

```

244

245

### Reloading and Caching

246

247

```python

248

# Force recompilation even if source hasn't changed

249

%%cython -f

250

def updated_function():

251

return "New implementation"

252

253

# Cython magic automatically caches compiled extensions

254

# Only recompiles when source code changes

255

```

256

257

### Integration with Existing Python Variables

258

259

```python

260

# Define data in Python

261

import numpy as np

262

data = np.random.random(1000000)

263

threshold = 0.5

264

```

265

266

```cython

267

%%cython

268

import numpy as np

269

270

def count_above_threshold(double[:] arr, double thresh):

271

"""Count elements above threshold."""

272

cdef int count = 0

273

cdef int i

274

275

for i in range(arr.shape[0]):

276

if arr[i] > thresh:

277

count += 1

278

279

return count

280

281

# Use Python variables directly

282

result = count_above_threshold(data, threshold)

283

print(f"Found {result} elements above {threshold}")

284

```

285

286

### Error Handling and Debugging

287

288

```cython

289

%%cython

290

def division_function(int a, int b):

291

"""Function that demonstrates error handling."""

292

if b == 0:

293

raise ValueError("Division by zero!")

294

return a / b

295

296

try:

297

result = division_function(10, 0)

298

except ValueError as e:

299

print(f"Error: {e}")

300

```

301

302

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.