如何使用 Sphinx 的 autodoc 来记录类的 __init__(self) 方法?

发布于 2024-10-31 12:38:06 字数 417 浏览 7 评论 0原文

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

.. automodule:: mymodule
    :members:

并且

..autoclass:: MyClass
    :members:

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

autoclass_content = 'both'

Sphinx doesn't generate docs for __init__(self) by default. I have tried the following:

.. automodule:: mymodule
    :members:

and

..autoclass:: MyClass
    :members:

In conf.py, setting the following only appends the __init__(self) docstring to the class docstring (the Sphinx autodoc documentation seems to agree that this is the expected behavior, but mentions nothing regarding the problem I'm trying to solve):

autoclass_content = 'both'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

忆离笙 2024-11-07 12:38:06

以下是三种替代方案:

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

    def Skip(应用程序、内容、名称、obj、would_skip、选项):
        如果名称==“__init__”:
            返回错误
        返回将跳过
    
    默认设置(应用程序):
        app.connect("autodoc-skip-member", 跳过)
    

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

  2. 特殊成员< /a> 选项在 Sphinx 1.1 中添加 。它使“特殊”成员(名称如 __special__ 的成员)由 autodoc 记录。

    自 Sphinx 1.2 起,此选项采用参数,这使得它比以前更有用。

  3. 使用自动方法

    .. autoclass:: MyClass     
       :成员: 
    
       .. 自动方法:: __init__
    

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

Here are three alternatives:

  1. To ensure that __init__() is always documented, you can use autodoc-skip-member in conf.py. Like this:

    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)
    

    This explicitly defines __init__ not to be skipped (which it is by default). This configuration is specified once, and it does not require any additional markup for every class in the .rst source.

  2. The special-members option was added in Sphinx 1.1. It makes "special" members (those with names like __special__) be documented by autodoc.

    Since Sphinx 1.2, this option takes arguments which makes it more useful than it was previously.

  3. Use automethod:

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

    This has to be added for every class (cannot be used with automodule, as pointed out in a comment to the first revision of this answer).

祁梦 2024-11-07 12:38:06

你很接近。您可以使用 autoclass_content< conf.py 文件中的 /a> 选项:

autoclass_content = 'both'

You were close. You can use the autoclass_content option in your conf.py file:

autoclass_content = 'both'
谜兔 2024-11-07 12:38:06

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

例子:

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

Even though this is an older post, for those who are looking it up as of now, there is also another solution introduced in version 1.8. According to the documentation, You can add the special-members key in the autodoc_default_options to your conf.py.

Example:

autodoc_default_options = {
    'members': True,
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__'
}
夜灵血窟げ 2024-11-07 12:38:06

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

最近,我采用了最好的实现,并将其作为我的 Python 项目之一的一部分(这是文档)。 实现基本上可以归结为:

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< /code> 选项还可以启用诸如 __weakref__ (在所有新式类上可用,据我所知)之类的属性的文档,我认为这些属性是噪音并且根本没有用。回调方法避免了这种情况(因为它仅适用于函数/方法并忽略其他属性)。

Over the past years I've written several variants of autodoc-skip-member callbacks for various unrelated Python projects because I wanted methods like __init__(), __enter__() and __exit__() to show up in my API documentation (after all, these "special methods" are part of the API and what better place to document them than inside the special method's docstring).

Recently I took the best implementation and made it part of one of my Python projects (here's the documentation). The implementation basically comes down to this:

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

Yes, there's more documentation than logic :-). The advantage of defining an autodoc-skip-member callback like this over the use of the special-members option (for me) is that the special-members option also enables documentation of properties like __weakref__ (available on all new-style classes, AFAIK) which I consider noise and not useful at all. The callback approach avoids this (because it only works on functions/methods and ignores other attributes).

简单爱 2024-11-07 12:38:06

只要此提交获得批准: 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

As long as this commit approved: https://github.com/sphinx-doc/sphinx/pull/9154, in the next sphinx version (>4.1.2) will be possible to:

..autoclass:: MyClass1
    :members:
    :class-doc-from: class


..autoclass:: MyClass2
    :members:
    :class-doc-from: init
幸福丶如此 2024-11-07 12:38:06

这是一个变体,仅在有参数时才包含 __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)

This is a variant which only includes __init__ if it has arguments:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文