doctest.script_from_examples()

doctest.script_from_examples(s)

Convert text with examples to a script.

Argument s is a string containing doctest examples. The string is converted to a Python script, where doctest examples in s are converted to regular code, and everything else is converted to Python comments. The generated script is returned as a string. For example,

import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))

displays:

# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3

This function is used internally by other functions (see below), but can also be useful when you want to transform an interactive Python session into a Python script.

doc_python
2016-10-07 17:32:14
Comments
Leave a Comment

Please login to continue.