我更喜欢在我声明参数的同一行记录每个参数(根据需要)以便应用 干。
如果我有这样的代码:
def foo(
flab_nickers, # a series of under garments to process
has_polka_dots=False,
needs_pressing=False # Whether the list of garments should all be pressed
):
...
如何避免重复doc字符串中的参数并保留参数说明?
我想避免:
def foo(
flab_nickers, # a series of under garments to process
has_polka_dots=False,
needs_pressing=False # Whether the list of garments should all be pressed
):
'''Foo does whatever.
* flab_nickers - a series of under garments to process
* needs_pressing - Whether the list of garments should all be pressed.
[Default False.]
在python 2.6或python 3中是否可以使用某种装饰器操作?还有其他方法吗?
我会这样做的。
从这段代码开始。
def foo(
flab_nickers, # a series of under garments to process
has_polka_dots=False,
needs_pressing=False # Whether the list of garments should all be pressed
):
...
我会写一个解析器来抓取函数参数定义并构建以下内容:
def foo(
flab_nickers,
has_polka_dots=False,
needs_pressing=False,
):
"""foo
:param flab_nickers: a series of under garments to process
:type flab_nickers: list or tuple
:param has_polka_dots: default False
:type has_polka_dots: bool
:param needs_pressing: default False, Whether the list of garments should all be pressed
:type needs_pressing: bool
"""
...
这是一些非常直接的正则表达式处理各种参数字符串模式来填充文档模板。
许多优秀的Python IDE(例如PyCharm)都了解默认的Sphinx param
IDE认为不符合声明类型的范围中的符号甚至标志变量/方法。
注意代码中的额外逗号;这只是为了使事情保持一致。它没有任何害处,它可能会简化未来的事情。
您还可以尝试使用Python编译器来获取解析树,修改它并发出更新代码。我已经为其他语言(不是Python)做了这个,所以我对它有点了解,但不知道它在Python中的支持程度如何。
此外,这是一次性转型。
函数定义中的原始内联注释并不真正遵循DRY,因为它是一种注释,使用非正式语言,并且除了最复杂的工具之外不能使用。
Sphinx评论更接近DRY,因为它们采用RST标记语言,使得使用普通文本解析工具更容易处理 docutils
。
如果工具可以使用它,那只是DRY。
有用的链接:
https://pythonhosted.org/an_example_pypi_project/sphinx.html#function-definitions
http://sphinx-doc.org/domains.html#id1
注释旨在部分解决Python 3中的这个问题:
http://www.python.org/dev/peps/pep-3107/
我不确定是否还有任何将这些应用于Sphinx的工作。
没有预处理器就不能这样做,因为一旦编译了源代码,Python就不存在注释。为避免重复自己,请删除注释并仅在docstring中记录参数,这是记录参数的标准方法。