【问题标题】:Document object modification in function using Sphinx使用 Sphinx 在函数中修改文档对象
【发布时间】:2021-07-27 19:48:39
【问题描述】:

我有一个函数比如:

def my_function(obj, X):
    """My function.

    :param obj: An instance of object.
    :type obj: object

    :param A: An array
    :type A: :class:`numpy.ndarray`

    """

    obj.fs['X'] = X.shape

    obj.d['v'] = obj.fs['X'][0]
    obj.d['t'] = obj.fs['X'][1]
    obj.d['m'] = obj.fs['X'][2]

    #: Comment here
    hv = obj.fs['Uh'] = (obj.d['h'], obj.d['v'])
    hh = obj.fs['Vh'] = (obj.d['h'], obj.d['h'])
    h1 = obj.fs['bh'] = (obj.d['h'], 1)

    # Etc...

    return None

我使用 Sphinx 记录了这个函数:

.. autofunction:: path.my_function

我想要一种记录代码块的方法。我知道有#: Comment,但似乎不适用于.. autofunction::

【问题讨论】:

标签: python python-sphinx autodoc


【解决方案1】:

我认为这是一种误解,因为 API 中记录的是构造(例如类、方法、函数等)的签名,而不是代码的内部部分。正如提到的in @mzjn's post,这是 PEP 257 定义为使用文档字符串的内容。

对此的一个例外是记录属性(这是在 Sphinx 中使用的 #: 语法),但通常您只公开类级别和模块级别的用户定义属性(绝不是函数范围的属性)。

在您的描述中,正确的选项是使用a code region 在构造中拆分内部区域。 (但请注意,这种内部文档的风格应该只关注那些将目光超越 API 并进入源代码的开发人员。函数实现的任何功能都应该根据参数和返回以文本形式记录在文档字符串中,从而隐藏任何内部结构。)

def my_function(obj, X):
    """My function.

    :param obj: An instance of object.
    :type obj: object

    :param A: An array
    :type A: :class:`numpy.ndarray`

    """

    # region Adding attributes to argument object.
    obj.fs['X'] = X.shape

    obj.d['v'] = obj.fs['X'][0]
    obj.d['t'] = obj.fs['X'][1]
    obj.d['m'] = obj.fs['X'][2]
    # endregion
    
    # region USUALLY A ONE-LINER HERE
    # If the above isn't enough expand it by writing more comment lines.
    hv = obj.fs['Uh'] = (obj.d['h'], obj.d['v'])  # Inline comment.
    hh = obj.fs['Vh'] = (obj.d['h'], obj.d['h'])
    h1 = obj.fs['bh'] = (obj.d['h'], 1)
    # endregion

    # Etc...

    return None

但是,在罕见的用例中,上述情况并非没有一些可能的例外。问题是 autodoc 扩展遵循上面解释的普遍规则,因此对于 .. autofunction::..automethod:: 指令,文档明确指出:

.. autofunction::

这些工作与 autoclass 等完全一样,但不提供用于自动成员文档的选项。

一个违反先前逻辑并且看起来与您的用例相似的示例是记录一个向创建的实例添加额外属性的工厂方法。您可以通过cross-referencing 额外属性在文档字符串或.rst 文件中以文本形式说明这一点。但是,这仍然会违反Principle of least astonishment 和通常的封装逻辑,因为用户希望类/对象的属性是对象最初声明时使用的属性。

但是,如果您真的想要这种 OO 设计,有一个技术解决方案。而不是简单地使用:

.. autofunction:: path.my_function

使用 Python 域 .. py:attribute::.rst 文件中声明变量。这样做的缺点是它不会提取您在源代码中使用:# 语法编写的文本。但是,它确实允许完全按照您在原始问题中的意图实施文档。

.. autofunction:: path.my_function

   .. py:attribute:: path.my_function.hv 
      
      Some text about the attribute.

   .. py:attribute:: path.my_function.hh 
      
      Some text about the attribute.

   .. py:attribute:: path.my_function.h1 
      
      Some text about the attribute.

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多