0
# Parameter Inspection
1
2
Tools for analyzing and inspecting notebook parameters before execution, enabling validation and dynamic parameter discovery. The inspection system analyzes parameter cells to infer types, defaults, and documentation.
3
4
## Capabilities
5
6
### Inspect Notebook Parameters
7
8
Returns the inferred notebook parameters from the parameters cell.
9
10
```python { .api }
11
def inspect_notebook(
12
notebook_path: str | Path,
13
parameters: dict = None
14
) -> dict[str, Parameter]:
15
"""
16
Return the inferred notebook parameters.
17
18
Parameters:
19
- notebook_path: Path to notebook
20
- parameters: Arbitrary keyword arguments to pass to the notebook parameters
21
22
Returns:
23
Dict[str, dict]: Mapping of parameter name to parameter dictionary containing:
24
- name: Parameter name
25
- inferred_type_name: String representation of inferred type
26
- default: String representation of default value
27
- help: Help text/description
28
"""
29
```
30
31
**Usage Examples:**
32
33
```python
34
import papermill as pm
35
36
# Basic parameter inspection
37
params = pm.inspect_notebook('analysis.ipynb')
38
print(f"Found parameters: {list(params.keys())}")
39
40
# Inspect with parameter overrides
41
params = pm.inspect_notebook(
42
'notebook.ipynb',
43
parameters={'base_path': '/data'}
44
)
45
46
# Access parameter details
47
for name, info in params.items():
48
print(f"Parameter: {name}")
49
print(f" Type: {info['inferred_type_name']}")
50
print(f" Default: {info['default']}")
51
print(f" Help: {info['help']}")
52
```
53
54
### Display Notebook Help
55
56
Displays help information about notebook parameters in a CLI-friendly format.
57
58
```python { .api }
59
def display_notebook_help(
60
ctx: click.Context,
61
notebook_path: str,
62
parameters: dict
63
) -> int:
64
"""
65
Display help on notebook parameters.
66
67
Parameters:
68
- ctx: Click context
69
- notebook_path: Path to the notebook to be inspected
70
- parameters: Parameter overrides for path templating
71
72
Returns:
73
int: Exit code (0 for success, 1 for failure)
74
"""
75
```
76
77
**Usage Example:**
78
79
```python
80
import click
81
from papermill.inspection import display_notebook_help
82
83
# Create click context
84
ctx = click.Context(click.Command('test'))
85
86
# Display help
87
exit_code = display_notebook_help(
88
ctx,
89
'notebook.ipynb',
90
{'base_path': '/data'}
91
)
92
```
93
94
## Internal Functions
95
96
### Open Notebook with Parameters
97
98
Internal utility for opening and parameterizing notebook paths.
99
100
```python { .api }
101
def _open_notebook(
102
notebook_path: str,
103
parameters: dict
104
) -> nbformat.NotebookNode:
105
"""
106
Opens notebook with parameter path substitution.
107
108
Parameters:
109
- notebook_path: Path to notebook (may contain parameter templates)
110
- parameters: Parameters for path templating
111
112
Returns:
113
NotebookNode: Loaded notebook
114
"""
115
```
116
117
### Infer Parameters from Notebook
118
119
Internal function that performs the actual parameter inference from notebook cells.
120
121
```python { .api }
122
def _infer_parameters(
123
nb: nbformat.NotebookNode,
124
name: str = None,
125
language: str = None
126
) -> list[Parameter]:
127
"""
128
Infer the notebook parameters.
129
130
Parameters:
131
- nb: Notebook to analyze
132
- name: Kernel name override
133
- language: Language override
134
135
Returns:
136
List[Parameter]: List of parameters with metadata (name, inferred_type_name, default, help)
137
"""
138
```
139
140
## Advanced Usage
141
142
### Parameter Validation Workflow
143
144
```python
145
import papermill as pm
146
147
def validate_and_execute(notebook_path, user_params):
148
# Inspect expected parameters
149
expected_params = pm.inspect_notebook(notebook_path)
150
151
# Validate user provided all required parameters
152
required_params = {
153
name: info for name, info in expected_params.items()
154
if info['default'] is None
155
}
156
157
missing_params = set(required_params.keys()) - set(user_params.keys())
158
if missing_params:
159
raise ValueError(f"Missing required parameters: {missing_params}")
160
161
# Check for unknown parameters
162
unknown_params = set(user_params.keys()) - set(expected_params.keys())
163
if unknown_params:
164
print(f"Warning: Unknown parameters: {unknown_params}")
165
166
# Execute with validated parameters
167
return pm.execute_notebook(
168
notebook_path,
169
'output.ipynb',
170
parameters=user_params
171
)
172
173
# Usage
174
try:
175
result = validate_and_execute(
176
'analysis.ipynb',
177
{'dataset': 'sales_2024.csv', 'threshold': 0.8}
178
)
179
print("Execution successful!")
180
except ValueError as e:
181
print(f"Validation error: {e}")
182
```
183
184
### Dynamic Parameter Discovery
185
186
```python
187
import papermill as pm
188
189
def discover_notebook_interface(notebook_path):
190
"""Discover complete notebook interface"""
191
params = pm.inspect_notebook(notebook_path)
192
193
interface = {
194
'required_parameters': [],
195
'optional_parameters': [],
196
'parameter_types': {},
197
'parameter_help': {}
198
}
199
200
for name, info in params.items():
201
if info['default'] is None or info['default'] == 'None':
202
interface['required_parameters'].append(name)
203
else:
204
interface['optional_parameters'].append(name)
205
206
interface['parameter_types'][name] = info['inferred_type_name']
207
interface['parameter_help'][name] = info['help']
208
209
return interface
210
211
# Usage
212
interface = discover_notebook_interface('notebook.ipynb')
213
print(f"Required: {interface['required_parameters']}")
214
print(f"Optional: {interface['optional_parameters']}")
215
```
216
217
### Batch Parameter Analysis
218
219
```python
220
import os
221
import papermill as pm
222
from pathlib import Path
223
224
def analyze_notebook_directory(directory_path):
225
"""Analyze all notebooks in a directory"""
226
notebook_dir = Path(directory_path)
227
analysis_results = {}
228
229
for notebook_file in notebook_dir.glob('*.ipynb'):
230
try:
231
params = pm.inspect_notebook(str(notebook_file))
232
analysis_results[notebook_file.name] = {
233
'parameter_count': len(params),
234
'parameters': params,
235
'has_parameters_cell': len(params) > 0
236
}
237
except Exception as e:
238
analysis_results[notebook_file.name] = {
239
'error': str(e)
240
}
241
242
return analysis_results
243
244
# Usage
245
results = analyze_notebook_directory('/path/to/notebooks')
246
for notebook, info in results.items():
247
if 'error' in info:
248
print(f"{notebook}: ERROR - {info['error']}")
249
else:
250
print(f"{notebook}: {info['parameter_count']} parameters")
251
```