【问题标题】:How to use Sphinx's autodoc to document a class's __init__(self) method?如何使用 Sphinx 的 autodoc 来记录类的 __init__(self) 方法?
【发布时间】:2011-08-01 17:43:23
【问题描述】:

默认情况下,Sphinx 不会为 __init__(self) 生成文档。我尝试了以下方法:

.. automodule:: mymodule
    :members:

..autoclass:: MyClass
    :members:

在 conf.py 中,设置以下内容仅将 __init__(self) 文档字符串附加到类文档字符串(the Sphinx autodoc documentation 似乎同意这是预期的行为,但没有提及我要解决的问题) :

autoclass_content = 'both'

【问题讨论】:

  • 不,这不是今天的文档所写的,至少:"both" Both the class’ and the __init__ method’s docstring are concatenated and inserted. -> 因此,它不应该只是__init__(self),还应该是类文档字符串,如果你有的话那。你能提供一个测试用例吗,因为如果是这样,那感觉就像一个错误,对吧?

标签: python python-sphinx autodoc


【解决方案1】:

这里有三种选择:

  1. 为确保始终记录__init__(),您可以在conf.py 中使用autodoc-skip-member。像这样:

    def skip(app, what, name, obj, would_skip, options):
        if name == "__init__":
            return False
        return would_skip
    
    def setup(app):
        app.connect("autodoc-skip-member", skip)
    

    这明确定义了__init__ 不被跳过(默认情况下)。此配置只指定一次,并且不需要为 .rst 源中的每个类添加任何附加标记。

  2. special-members 选项是 added in Sphinx 1.1。它使“特殊”成员(名称如 __special__)被 autodoc 记录。

    自 Sphinx 1.2 以来,此选项采用参数,使其比以前更有用。

  3. 使用automethod

    .. autoclass:: MyClass     
       :members: 
    
       .. automethod:: __init__
    

    这必须为每个类添加(不能与automodule 一起使用,正如对此答案第一版的评论中指出的那样)。

【讨论】:

  • 这对自动模块没有帮助,因为它必须添加到每个类中。
  • 第一个替代方案奏效了。就我而言,它比第二种和第三种选择要好,因为它不需要编辑 .rst 文件。
  • 在 Sphinx 1.2.1 中,special-members 使用 automodule 可以正常工作。使用:special-members: __init__ 仅记录__init__
【解决方案2】:

你很亲密。您可以在 conf.py 文件中使用 autoclass_content 选项:

autoclass_content = 'both'

【讨论】:

  • @MichaelMrozek:我也想知道这个问题......你明白这个答案的高投票率吗?起初,它看起来像是一个应该被清除的答案。
  • 我尝试设置 autoclass_content = 'both' 选项,该选项确实记录了 init 方法,但它使自动摘要出现了两次。
  • 这应该是公认的答案。比较简单,参考sphinx官方文档。
  • 这是最好的方法,它与自动摘要完美配合,结果比special-methods好得多,前者在类的开头添加构造函数文档,后者添加文档的单独__init__ 方法。
【解决方案3】:

在过去的几年里,我为各种不相关的 Python 项目编写了 autodoc-skip-member 回调的几种变体,因为我希望像 __init__()__enter__()__exit__() 这样的方法出现在我的 API 文档中(毕竟,这些“特殊方法”是 API 的一部分,还有什么比在特殊方法的文档字符串中更好地记录它们的地方)。

最近我采用了最好的实现并将其作为我的 Python 项目之一 (here's the documentation) 的一部分。 The implementation 基本上归结为:

import types

def setup(app):
    """Enable Sphinx customizations."""
    enable_special_methods(app)


def enable_special_methods(app):
    """
    Enable documenting "special methods" using the autodoc_ extension.

    :param app: The Sphinx application object.

    This function connects the :func:`special_methods_callback()` function to
    ``autodoc-skip-member`` events.

    .. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html
    """
    app.connect('autodoc-skip-member', special_methods_callback)


def special_methods_callback(app, what, name, obj, skip, options):
    """
    Enable documenting "special methods" using the autodoc_ extension.

    Refer to :func:`enable_special_methods()` to enable the use of this
    function (you probably don't want to call
    :func:`special_methods_callback()` directly).

    This function implements a callback for ``autodoc-skip-member`` events to
    include documented "special methods" (method names with two leading and two
    trailing underscores) in your documentation. The result is similar to the
    use of the ``special-members`` flag with one big difference: Special
    methods are included but other types of members are ignored. This means
    that attributes like ``__weakref__`` will always be ignored (this was my
    main annoyance with the ``special-members`` flag).

    The parameters expected by this function are those defined for Sphinx event
    callback functions (i.e. I'm not going to document them here :-).
    """
    if getattr(obj, '__doc__', None) and isinstance(obj, (types.FunctionType, types.MethodType)):
        return False
    else:
        return skip

是的,文档多于逻辑 :-)。与使用 special-members 选项(对我而言)相比,像这样定义 autodoc-skip-member 回调的优势在于,special-members 选项还可以记录 __weakref__ 之类的属性(适用于所有新型类,AFAIK ) 我认为这是噪音,根本没有用。回调方法避免了这种情况(因为它仅适用于函数/方法而忽略其他属性)。

【讨论】:

  • 这个怎么用?看来该方法必须命名为 setup(app) 才能由 Sphinx 执行。
  • 我不完全理解,但如果你想剖析自己,请参阅 xolox 的 implementation。我相信他构建了一个狮身人面像扩展,将回调连接到 autodoc-skip-member 事件。当 sphinx 试图确定是否应该包含/跳过某些内容时,该事件会触发,并且他的代码会运行。如果他的代码检测到用户明确定义的 special 成员(像经常发生的那样继承),那么它会告诉 Sphinx 包含它。这样你就可以记录你自己写的特殊成员
  • 感谢 Andrew 的澄清,是的,您是正确的 oarfish,需要设置功能。我已将其添加到示例中以避免进一步混淆。
  • @JoelB:我的帖子中的示例代码假定您的__init__ 方法具有非空文档字符串。是吗?
【解决方案4】:

尽管这是一篇较旧的帖子,但对于那些正在查找它的人来说,1.8 版中还引入了另一种解决方案。根据documentation,您可以将autodoc_default_options中的special-member键添加到您的conf.py中。

例子:

autodoc_default_options = {
    'members': True,
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__'
}

【讨论】:

    【解决方案5】:

    这是一个仅包含 __init__ 参数的变体:

    import inspect
    
    def skip_init_without_args(app, what, name, obj, would_skip, options):
        if name == '__init__':
            func = getattr(obj, '__init__')
            spec = inspect.getfullargspec(func)
            return not spec.args and not spec.varargs and not spec.varkw and not spec.kwonlyargs
        return would_skip
    
    def setup(app):
        app.connect("autodoc-skip-member", skip_init_without_args)
    

    【讨论】:

      【解决方案6】:

      只要此提交批准:https://github.com/sphinx-doc/sphinx/pull/9154,在下一个 sphinx 版本(>4.1.2)中就可以:

      ..autoclass:: MyClass1
          :members:
          :class-doc-from: "class"
      
      
      ..autoclass:: MyClass2
          :members:
          :class-doc-from: "init"
      

      【讨论】:

        猜你喜欢
        • 2015-02-04
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多