从docstring生成pep 484类型注释
doc484的Python项目详细描述
从docstrings生成pep 484类型注释
doc484提供一个脚本,用于在docstring中查找类型声明并将其转换为pep 484类型注释。它支持三个主要的docstring约定numpy、google和restructuredText (sphinx)
无论您选择何种docstring约定,在docstring中声明的类型都应该遵循PEP 484中的准则,特别是在必要时使用typing模块。
为什么要用这个?
如果您至少对其中的两个回答是肯定的,则此项目可能适合您:
- 您一直支持Python2.7,因此必须使用类型注释,而不是3.5+中支持的类型注释 <> LI>您的项目具有现有的文档字符串,这些类型已经基本上是正确的
- 您会发现维护和理解参数描述旁边指定的类型更容易
示例
基本
之前
fromtypingimportOptionaldefmaxlines(input,numlines=None):"""
Trim a string to a maximum number of lines.
Parameters
----------
input : str
numlines : Optional[int]
maximum number of lines
Returns
-------
str
"""ifnumlinesisNone:returninputreturn'\n'.join(input.split('\n')[:numlines])
在doc484
之后fromtypingimportOptionaldefmaxlines(input,numlines=None):# type: (str, Optional[int]) -> str""" Trim a string to a maximum number of lines. Parameters ---------- input : str numlines : Optional[int] maximum number of lines Returns ------- str """ifnumlinesisNone:returninputreturn'\n'.join(input.split('\n')[:numlines])
文件现在可以由mypy或pycharm正确检查。
高级
一个更复杂的示例演示了在docstring中指定类型所增加的一些可读性。 下面我们使用numpy格式来记录元组生成器:
之前
fromtypingimport*defitercount(input,char):"""
Iterate over input strings and yield a tuple of the string with `char`
removed, and the number of occurrences of `char`.
Parameters
----------
input : Iterable[str]
char : str
character to remove and count
Yields
------
stripped : str
input string with all occurrences of `char` removed
count : int
number of occurrences of `char`
"""forxininput:yieldx.strip(char),x.count(char)
在doc484
之后fromtypingimport*defitercount(input,char):# type: (Iterable[str], str) -> Iterator[Tuple[str, int]]""" Iterate over input strings and yield a tuple of the string with `char` removed, and the number of occurrences of `char`. Parameters ---------- input : Iterable[str] char : str character to remove and count Yields ------ stripped : str input string with all occurrences of `char` removed count : int number of occurrences of `char` """forxininput:yieldx.strip(char),x.count(char)
安装
pip install doc484
用法
doc484 -h
默认情况下,doc484将不修改文件,而是打印出要修改的内容的差异。准备好进行更改后,添加--write标志。
查看scripts目录以获取如何在git或mercurial存储库中的修改文件上自动运行doc484的示例。
配置
可以使用ini样式的配置文件覆盖任何命令行选项。 默认情况下,doc484在当前工作目录中查找setup.cfg文件,但也可以使用--config选项显式地提供配置。
例如,要覆盖转换时要使用的进程数,并指定项目的docstring格式,请将其添加到setup.cfg中,并从该配置文件所在的目录运行doc484:
[doc484]processes=12format=numpy
待办事项
- 自动插入typing导入
- 添加选项以将docstring转换为函数注释(对于python 3.5+)
- 完成对非PEP44-兼容文档字符串的修复支持(如{TT11}$)
- 是否将doctypes实用程序脚本转换为python?