在Sphinx中,是否有办法在声明参数时记录它们?

11 投票
3 回答
9515 浏览
提问于 2025-04-15 18:51

我喜欢在声明参数的同一行上记录每个参数(根据需要),这样可以遵循D.R.Y.原则,避免重复。

如果我的代码是这样的:

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中,有没有什么方法可以通过某种装饰器来实现?还有其他办法吗?

3 个回答

1

你不能这样做,因为在Python编译后,注释就不存在了。为了避免重复,你可以删掉注释,只在文档字符串里说明参数,这也是记录你参数的标准方式。

5

注解是为了部分解决这个问题而在Python 3中引入的:

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

我不确定这些注解是否已经在Sphinx中得到了应用。

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开发环境(比如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

撰写回答