11

我更喜欢在声明参数的同一行记录每个参数(根据需要),以便应用DRY

如果我有这样的代码:

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, # 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 中是否可行?还有其他方法吗?

4

3 回答 3

8

我会这样做。

从此代码开始。

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)理解默认的 Sphinxparam表示法,甚至在 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

于 2010-02-03T19:27:46.990 回答
5

注释旨在部分解决 Python 3 中的这个问题:

http://www.python.org/dev/peps/pep-3107/

我不确定在将这些应用到 Sphinx 上是否有任何工作。

于 2013-08-26T19:57:50.443 回答
1

如果没有预处理器,你就无法做到这一点,因为一旦编译了源代码,Python 就不存在注释。为避免重复,请删除注释并仅在文档字符串中记录参数,这是记录参数的标准方式。

于 2010-02-03T19:31:45.980 回答