or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cleaning.mdconfiguration.mddevelopment-tools.mddocumentation.mdexport.mdgit-integration.mdindex.mdrelease-management.mdsynchronization.mdtesting.md

export.mddocs/

0

# Notebook Export

1

2

Convert Jupyter notebook cells to Python modules with proper imports, documentation, and structure. The export system processes notebook cells marked with special directives and creates well-structured Python packages.

3

4

## Capabilities

5

6

### Main Export Function

7

8

Export notebooks to Python modules based on project configuration.

9

10

```python { .api }

11

def nb_export():

12

"""

13

Export notebooks to Python modules.

14

15

Processes all notebooks in the project's nbs_path, extracting cells marked

16

with #|export directives and converting them to proper Python modules

17

in the lib_path directory. Handles imports, documentation, and code structure.

18

"""

19

```

20

21

**Usage Example:**

22

23

```python

24

from nbdev.export import nb_export

25

26

# Export all notebooks in project to Python modules

27

nb_export()

28

```

29

30

### Export Processor

31

32

Core processor class for handling notebook-to-module conversion.

33

34

```python { .api }

35

class ExportModuleProc:

36

"""

37

A processor which exports code to a module.

38

39

Processes notebook cells and organizes them into Python modules

40

based on export directives and default export destinations.

41

"""

42

43

def begin(self):

44

"""Initialize module collections and __all__ tracking."""

45

46

def _default_exp_(self, cell, exp_to: str):

47

"""Set default export destination for subsequent cells."""

48

49

def _export_(self, cell, exp_to: str = None):

50

"""Export cell to module and include in __all__."""

51

52

def _exporti_(self, cell, exp_to: str = None):

53

"""Export cell to module without including in __all__."""

54

55

def __call__(self, cell):

56

"""Process a single notebook cell."""

57

```

58

59

**Usage Example:**

60

61

```python

62

from nbdev.export import ExportModuleProc

63

from nbdev.process import NBProcessor

64

65

# Create processor for a specific notebook

66

proc = ExportModuleProc()

67

processor = NBProcessor('example.ipynb', procs=[proc])

68

processor.process()

69

70

# Access exported modules

71

for module_name, cells in proc.modules.items():

72

print(f"Module {module_name}: {len(cells)} cells")

73

```

74

75

### Code Formatting

76

77

Format exported code using black for consistent style.

78

79

```python { .api }

80

def black_format(cell, force: bool = False):

81

"""

82

Processor to format code with black.

83

84

Args:

85

cell: Notebook cell to format

86

force: Turn black formatting on regardless of settings.ini

87

88

Formats cell source code using black if black_formatting is enabled

89

in configuration or force is True. Only processes code cells.

90

91

Raises:

92

ImportError: If black is not installed but formatting is requested

93

"""

94

```

95

96

**Usage Example:**

97

98

```python

99

from nbdev.export import black_format

100

from execnb.nbio import NbCell

101

102

# Create a code cell

103

cell = NbCell('def hello():\n print("world")', 'code')

104

105

# Format with black

106

black_format(cell, force=True)

107

print(cell.source) # Properly formatted code

108

```

109

110

### Magic Command Processing

111

112

Remove or process IPython magic commands from exported code.

113

114

```python { .api }

115

def scrub_magics(cell):

116

"""

117

Remove IPython magics from cell source.

118

119

Args:

120

cell: Notebook cell to process

121

122

Removes or converts IPython magic commands (lines starting with % or %%)

123

that shouldn't appear in exported Python modules.

124

"""

125

```

126

127

### Optional Processors

128

129

Get list of optional processors for export pipeline.

130

131

```python { .api }

132

def optional_procs():

133

"""

134

Get list of optional processors for export.

135

136

Returns:

137

List of processor classes that can be optionally included

138

in the export pipeline based on configuration settings.

139

140

Optional processors may include:

141

- black_format: Code formatting

142

- Additional custom processors

143

"""

144

```

145

146

## Export Directives

147

148

nbdev uses special cell directives to control export behavior:

149

150

### Basic Export Directives

151

152

- `#|default_exp module_name`: Set default export destination

153

- `#|export`: Export cell to default module and include in __all__

154

- `#|exporti`: Export cell to default module but don't include in __all__

155

- `#|exports`: Alias for #|export

156

157

### Targeted Export

158

159

- `#|export module_name`: Export to specific module

160

- `#|exporti module_name`: Export to specific module without __all__

161

162

**Usage in Notebooks:**

163

164

```python

165

# In notebook cell 1:

166

#|default_exp core

167

168

# In notebook cell 2:

169

#|export

170

def public_function():

171

"""This will be in __all__"""

172

pass

173

174

# In notebook cell 3:

175

#|exporti

176

def _private_function():

177

"""This won't be in __all__"""

178

pass

179

180

# In notebook cell 4:

181

#|export utils

182

def utility_function():

183

"""This goes to utils module"""

184

pass

185

```

186

187

## Export Process

188

189

The export process follows these steps:

190

191

1. **Discovery**: Find all notebooks in `nbs_path`

192

2. **Processing**: Process each notebook through the export pipeline

193

3. **Cell Analysis**: Extract cells with export directives

194

4. **Module Generation**: Group cells by destination module

195

5. **Code Generation**: Create Python files with proper structure

196

6. **Import Handling**: Add necessary imports and __all__ declarations

197

7. **Formatting**: Apply black formatting if enabled

198

8. **File Writing**: Write modules to `lib_path` directory

199

200

**Complete Example:**

201

202

```python

203

from nbdev.export import nb_export, ExportModuleProc

204

from nbdev.config import get_config

205

206

# Check configuration

207

config = get_config()

208

print(f"Notebooks: {config.nbs_path}")

209

print(f"Library: {config.lib_path}")

210

211

# Export all notebooks

212

nb_export()

213

214

# The export creates:

215

# - Python modules in lib_path

216

# - Proper __init__.py files

217

# - __all__ declarations

218

# - Import statements

219

# - Documentation strings

220

```

221

222

## Integration with nbdev Pipeline

223

224

The export system integrates with other nbdev components:

225

226

- **Configuration**: Uses settings from `get_config()`

227

- **Processing**: Leverages `NBProcessor` for cell handling

228

- **Documentation**: Exports docstrings for `show_doc`

229

- **Testing**: Exported modules can be tested with `nbdev_test`

230

- **Cleaning**: Works with `nbdev_clean` for notebook maintenance