Elysia Tools
Navigation
Development
Python docstrings: runnable extraction fixtures
Three original Python examples separate documentation from ordinary strings; all five doctests pass.
Samples
Entries inside this sample collection
Module and function documentation
Run the arithmetic fixture and extract docstrings with ast.get_docstring from the module and add function.
"""Synthetic arithmetic module."""
def add(left: int, right: int) -> int:
"""Return the sum of two integers.
>>> add(3, 5)
8
"""
return left + right
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
Class and method documentation
Run the Counter fixture; inspect the class and increment method separately.
class Counter:
"""A synthetic counter starting at zero."""
def __init__(self):
self.value = 0
def increment(self):
"""Increase the stored value by one.
>>> c = Counter()
>>> c.increment()
1
>>> c.increment()
2
"""
self.value += 1
return self.value
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
Strings that are not docstrings
Run normalize and inspect only its first statement for documentation.
LABEL = "This assigned string is data, not a docstring."
def normalize(text: str) -> str:
"""Remove outer whitespace and lowercase text.
>>> normalize(" HELLO ")
'hello'
"""
result = text.strip().lower()
"""This later expression is not the function docstring."""
return result
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=True)
Tools
Tools frequently paired with this sample
Related
Related sample collections
Related