or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdformatting.mdindex.mdjupyter.mdserver.mdtypes.md

jupyter.mddocs/

0

# Jupyter Notebook Support

1

2

Specialized formatting functions for Jupyter notebooks and individual notebook cells, with support for IPython magics, cell-specific formatting rules, and notebook JSON structure handling.

3

4

## Capabilities

5

6

### Cell Formatting

7

8

Format individual Jupyter notebook cells with special handling for IPython magics and trailing semicolons.

9

10

```python { .api }

11

def format_cell(src: str, *, fast: bool, mode: Mode) -> str:

12

"""

13

Format individual Jupyter notebook cell content.

14

15

Parameters:

16

- src: Cell source code to format

17

- fast: Skip AST safety checks if True

18

- mode: Mode configuration with is_ipynb=True recommended

19

20

Returns:

21

Formatted cell source code

22

23

Note:

24

- Handles IPython magics (%, %%, !, !!)

25

- Preserves trailing semicolons for output suppression

26

- Recognizes python_cell_magics configured in mode

27

28

Raises:

29

- InvalidInput: If cell source cannot be parsed

30

- NothingChanged: If no formatting changes needed

31

"""

32

```

33

34

### Notebook File Formatting

35

36

Format complete Jupyter notebook JSON strings, processing only Python code cells while preserving notebook structure.

37

38

```python { .api }

39

def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> str:

40

"""

41

Format complete Jupyter notebook JSON string.

42

43

Parameters:

44

- src_contents: Complete notebook JSON as string

45

- fast: Skip AST safety checks if True

46

- mode: Mode configuration controlling formatting

47

48

Returns:

49

Formatted notebook JSON string

50

51

Note:

52

- Only processes cells with Python kernels

53

- Preserves all notebook metadata and structure

54

- Handles cell magics and IPython-specific syntax

55

56

Raises:

57

- InvalidInput: If notebook JSON is invalid

58

- NothingChanged: If no formatting changes needed

59

"""

60

```

61

62

### Magic Command Support

63

64

Constants and utilities for handling IPython magic commands in notebook cells.

65

66

```python { .api }

67

# Set of recognized Python cell magic commands

68

PYTHON_CELL_MAGICS: set[str]

69

```

70

71

Common Python cell magics include:

72

- `%%time` - Time execution of cell

73

- `%%timeit` - Benchmark cell execution

74

- `%%capture` - Capture cell output

75

- `%%writefile` - Write cell contents to file

76

- `%%bash` - Execute cell as bash script (when containing Python)

77

- `%%python` - Explicit Python execution

78

- `%%script python` - Script execution

79

80

## Usage Examples

81

82

### Basic Cell Formatting

83

84

```python

85

import black

86

87

# Configure mode for Jupyter

88

mode = black.Mode(is_ipynb=True)

89

90

# Format a simple cell

91

cell_code = """

92

def calculate(x,y):

93

return x+y

94

result=calculate(5,3)

95

print(result)

96

"""

97

98

formatted_cell = black.format_cell(cell_code, fast=False, mode=mode)

99

print(formatted_cell)

100

# Output:

101

# def calculate(x, y):

102

# return x + y

103

#

104

# result = calculate(5, 3)

105

# print(result)

106

```

107

108

### Magic Command Handling

109

110

```python

111

# Cell with magic commands

112

magic_cell = """

113

%%time

114

import numpy as np

115

data=np.random.rand(1000,1000)

116

result=data.sum()

117

print(f"Sum: {result}")

118

"""

119

120

# Configure with custom cell magics

121

mode = black.Mode(

122

is_ipynb=True,

123

python_cell_magics={'%%time', '%%timeit', '%%capture', '%%writefile'}

124

)

125

126

formatted = black.format_cell(magic_cell, fast=False, mode=mode)

127

print(formatted)

128

# Output:

129

# %%time

130

# import numpy as np

131

#

132

# data = np.random.rand(1000, 1000)

133

# result = data.sum()

134

# print(f"Sum: {result}")

135

```

136

137

### Trailing Semicolon Preservation

138

139

```python

140

# Cell with output suppression

141

suppressed_cell = """

142

import matplotlib.pyplot as plt

143

plt.plot([1,2,3],[4,5,6]);

144

plt.show();

145

"""

146

147

formatted = black.format_cell(suppressed_cell, fast=False, mode=mode)

148

print(formatted)

149

# Output:

150

# import matplotlib.pyplot as plt

151

#

152

# plt.plot([1, 2, 3], [4, 5, 6]);

153

# plt.show();

154

# Note: Semicolons preserved for output suppression

155

```

156

157

### Complete Notebook Formatting

158

159

```python

160

import json

161

162

# Example notebook content

163

notebook_json = '''

164

{

165

"cells": [

166

{

167

"cell_type": "code",

168

"source": ["def hello(name):print(f'Hello {name}!')"],

169

"metadata": {},

170

"execution_count": null,

171

"outputs": []

172

}

173

],

174

"metadata": {

175

"kernelspec": {

176

"display_name": "Python 3",

177

"language": "python",

178

"name": "python3"

179

}

180

},

181

"nbformat": 4,

182

"nbformat_minor": 4

183

}

184

'''

185

186

# Format the entire notebook

187

mode = black.Mode(is_ipynb=True, line_length=79)

188

try:

189

formatted_notebook = black.format_ipynb_string(notebook_json, fast=False, mode=mode)

190

191

# Parse to verify formatting

192

notebook_data = json.loads(formatted_notebook)

193

print("Formatted cell source:")

194

for cell in notebook_data['cells']:

195

if cell['cell_type'] == 'code':

196

print(''.join(cell['source']))

197

198

except black.NothingChanged:

199

print("Notebook already properly formatted")

200

```

201

202

### File-based Notebook Formatting

203

204

```python

205

from pathlib import Path

206

207

# Format .ipynb file in place

208

notebook_path = Path("analysis.ipynb")

209

210

# Mode automatically detected from .ipynb extension

211

changed = black.format_file_in_place(

212

notebook_path,

213

fast=False,

214

mode=black.Mode(line_length=88), # is_ipynb set automatically

215

write_back=black.WriteBack.YES

216

)

217

218

if changed:

219

print(f"Formatted {notebook_path}")

220

else:

221

print(f"No changes needed for {notebook_path}")

222

```

223

224

### Mixed Magic and Python Code

225

226

```python

227

# Complex cell with multiple magics

228

complex_cell = '''

229

%load_ext autoreload

230

%autoreload 2

231

import pandas as pd

232

%%time

233

df = pd.read_csv("data.csv")

234

processed = df.groupby("category").sum()

235

!ls -la processed_data/

236

%%writefile output.py

237

print("Results saved")

238

'''

239

240

mode = black.Mode(

241

is_ipynb=True,

242

python_cell_magics={'%%time', '%%writefile'}

243

)

244

245

formatted = black.format_cell(complex_cell, fast=False, mode=mode)

246

print(formatted)

247

# Line magics (%) preserved, cell magics (%%) in python_cell_magics formatted

248

```

249

250

### Custom Magic Configuration

251

252

```python

253

# Define custom set of Python cell magics

254

custom_magics = {

255

'%%time',

256

'%%timeit',

257

'%%capture',

258

'%%writefile',

259

'%%bash', # If containing Python code

260

'%%script python',

261

'%%cython', # For Cython cells with Python syntax

262

}

263

264

mode = black.Mode(

265

is_ipynb=True,

266

python_cell_magics=custom_magics,

267

line_length=100 # Longer lines often preferred in notebooks

268

)

269

270

# Format with custom magic handling

271

formatted = black.format_cell(notebook_cell, fast=False, mode=mode)

272

```

273

274

## Error Handling

275

276

### Invalid Cell Content

277

278

```python

279

try:

280

# Cell with syntax errors

281

bad_cell = "def incomplete_function("

282

formatted = black.format_cell(bad_cell, fast=False, mode=mode)

283

except black.InvalidInput as e:

284

print(f"Cannot format cell: {e}")

285

# Handle syntax errors gracefully

286

```

287

288

### Notebook Structure Issues

289

290

```python

291

try:

292

# Malformed notebook JSON

293

bad_notebook = '{"cells": invalid json}'

294

formatted = black.format_ipynb_string(bad_notebook, fast=False, mode=mode)

295

except (json.JSONDecodeError, black.InvalidInput) as e:

296

print(f"Invalid notebook format: {e}")

297

```

298

299

## Integration with IPython

300

301

```python

302

# For use in IPython/Jupyter environments

303

def format_current_cell():

304

"""Format the current cell in Jupyter notebook."""

305

from IPython import get_ipython

306

307

ip = get_ipython()

308

if ip is None:

309

return "Not running in IPython"

310

311

# Get current cell content (implementation depends on Jupyter version)

312

cell_content = ip.user_ns.get('_i', '') # Last input

313

314

mode = black.Mode(is_ipynb=True)

315

try:

316

formatted = black.format_cell(cell_content, fast=False, mode=mode)

317

return formatted

318

except Exception as e:

319

return f"Formatting error: {e}"

320

321

# Use as magic command

322

%load_ext black # If black provides IPython extension

323

%black # Format current cell

324

```

325

326

## Types

327

328

```python { .api }

329

# Cell magic type

330

CellMagic = str

331

332

# Notebook cell content

333

CellSource = str | list[str]

334

335

# Complete notebook structure (simplified)

336

NotebookDict = dict[str, Any]

337

```