nbdev_mkdocs.docstring
run_examples_from_docstring(o, *, supress_stdout=False, supress_stderr=False, sub_dict=None, width=80, **kwargs)
¤
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 |
{} |
Exceptions:
Type | Description |
---|---|
ValueError |
if some params are missing from the kwargs |
RuntimeException |
if example fails |
Examples:
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
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") 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)