Skip to content

run_examples_from_docstring

nbdev_mkdocs.docstring.run_examples_from_docstring(o: Any, *, supress_stdout: bool = False, supress_stderr: bool = False, sub_dict: Optional[Dict[str, str]] = None, width: Optional[int] = 80, **kwargs: str) -> None ¤

Runs example from a docstring

Parses docstring of an objects looking for examples. The examples are then saved into files and executed in a separate process.

Note

Execution context is not the same as the one in the notebook because we want examples to work from user code. Make sure you compiled the library prior to executing the examples, otherwise you might be running them agains an old version of the library.

Parameters:

Name Type Description Default
o Any

an object, typically a function or a class, for which docstring is being parsed for examples

required
supress_stdout bool

omit stdout from output, typically due to security considerations

False
supress_stderr bool

omit stderr from output, typically due to security considerations

False
sub_dict Optional[Dict[str, str]]

a dictionary mapping regexp patterns into replacement strings used to mask stdout and stderr, typically used to mask sensitive information such as passwords

None
**kwargs str

arguments use to replace "{fill in param}" in docstring with the actual values when running examples

{}

Raises:

Type Description
ValueError

if some params are missing from the kwargs

RuntimeException

if example fails

Example
from  nbdev_mkdocs.docstring import run_examples_from_docstring

def f():
    ```python
    Example:
        print("Hello {fill in name}!")
        print("Goodbye {fill in other_name}!")
    ```
    pass


run_examples_from_docstring(f, name="John", other_name="Jane")

Note

The above docstring is autogenerated by docstring-gen library (https://github.com/airtai/docstring-gen)

Source code in nbdev_mkdocs/docstring.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def run_examples_from_docstring(
    o: Any,
    *,
    supress_stdout: bool = False,
    supress_stderr: bool = False,
    sub_dict: Optional[Dict[str, str]] = None,
    width: Optional[int] = 80,
    **kwargs: str,
) -> None:
    """Runs example from a docstring

    Parses docstring of an objects looking for examples. The examples are then saved into files and executed
    in a separate process.

    Note:
        Execution context is not the same as the one in the notebook because we want examples to work from
        user code. Make sure you compiled the library prior to executing the examples, otherwise you might
        be running them agains an old version of the library.

    Args:
        o: an object, typically a function or a class, for which docstring is being parsed for examples
        supress_stdout: omit stdout from output, typically due to security considerations
        supress_stderr: omit stderr from output, typically due to security considerations
        sub_dict: a dictionary mapping regexp patterns into replacement strings used to mask stdout and
            stderr, typically used to mask sensitive information such as passwords

        **kwargs: arguments use to replace "{fill in **param**}" in docstring with the actual values when running examples

    Raises:
        ValueError: if some params are missing from the **kwargs**
        RuntimeException: if example fails

    Example:
        ```python
        from  nbdev_mkdocs.docstring import run_examples_from_docstring

        def f():
            ```python
            Example:
                print("Hello {fill in name}!")
                print("Goodbye {fill in other_name}!")
            ```
            pass


        run_examples_from_docstring(f, name="John", other_name="Jane")
        ```

    !!! note

        The above docstring is autogenerated by docstring-gen library (https://github.com/airtai/docstring-gen)
    """
    console = Console(width=width)

    examples = _extract_examples_from_docstring(o)
    if len(examples) == 0:
        raise ValueError(f"No examples found in:\n{o.__doc__}")

    executable_examples = _replace_keywords(examples, **kwargs)
    for example, executable_example in zip(examples, executable_examples):
        with TemporaryDirectory() as d:
            cmd_path = (Path(d) / "example.py").absolute()
            with open(cmd_path, "w", encoding="utf-8") as f:
                f.write(executable_example)
            process = run(  # nosec: B603
                [sys.executable, str(cmd_path)], capture_output=True, text=True
            )
            group = Group(
                "Example:",
                Rule("code"),
                textwrap.indent(example, " " * 4),
                _format_output(
                    process.stdout,
                    title="stdout",
                    supress=supress_stdout,
                    sub_dict=sub_dict,
                    width=width,
                ),
                _format_output(
                    process.stderr,
                    title="stderr",
                    supress=supress_stderr,
                    sub_dict=sub_dict,
                    width=width,
                ),
            )
            #             print(Panel(panel_group, width=width))
            console.print(group)
            if process.returncode != 0:
                raise RuntimeError(process.stderr)