Elysia Tools
导航
开发
Python 文档字符串:可运行提取样例
三个原创 Python 示例区分文档与普通字符串,五项 doctest 全部通过。
案例
这个案例集合中的条目
模块与函数文档
运行加法样例,用 ast.get_docstring 提取模块及 add 函数文档。
"""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)
类与方法文档
运行 Counter 样例,分别检查类与 increment 方法。
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)
不是文档的字符串
运行 normalize,仅将函数第一条语句作为文档候选。
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)
工具
经常与该案例搭配使用的工具
相关内容
相关案例集合
相关内容