123

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'
mzjn
  • 48,958
  • 13
  • 128
  • 248
Jacob Marble
  • 28,555
  • 22
  • 67
  • 78
  • 1
    No, that is not what the documentation writes as of today, at least: `"both" Both the class’ and the __init__ method’s docstring are concatenated and inserted.` -> Therefore, it ought not to be only the `__init__(self)`, but also the class docstring if you have that. Can you provide a test case because if it is so, it feels like a bug, right? – László Papp Sep 08 '14 at 17:32

6 Answers6

127

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).

rozsasarpi
  • 1,621
  • 20
  • 34
mzjn
  • 48,958
  • 13
  • 128
  • 248
93

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

autoclass_content = 'both'
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
gotgenes
  • 38,661
  • 28
  • 100
  • 128
  • 1
    @MichaelMrozek: I am wondering about that, too... Did you understand the high upvote rate of this answer? At first, it looks like an answer that should be purged. – László Papp Sep 08 '14 at 17:34
  • 2
    I tried setting the `autoclass_content = 'both'` option, which did document the __init__ method, but it made the autosummary appear twice. – Stretch Apr 02 '15 at 13:21
  • 1
    This is the best way to do it, it works perfectly with autosummary and the result it's much better than `special-methods`, the former add the constructor doc right at the start of the class and the latter adds a separate `__init__` method to the doc. – Terseus Mar 23 '21 at 15:15
15

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__'
}
Adrian W
  • 4,563
  • 11
  • 38
  • 52
dheinz
  • 988
  • 10
  • 16
7

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).

joel
  • 6,359
  • 2
  • 30
  • 55
xolox
  • 4,888
  • 3
  • 24
  • 15
  • How do I use this? It seems the method must be named `setup(app)` in order to be executed by Sphinx. – oarfish Aug 16 '18 at 13:46
  • I don't understand it all, but see xolox's [implementation](https://github.com/xolox/python-humanfriendly/blob/master/humanfriendly/sphinx.py) if you want to dissect yourself. I believe he built a sphinx extension that connects a callback to the autodoc-skip-member event. When sphinx tries to figure out if something should be included/skipped that event fires, and his code runs. If his code detects a __special__ member that was defined explicitly by the user (inherited like often happens) then it tells Sphinx to include it. That way you can doc special members you write yourself – Andrew Jun 21 '19 at 18:19
  • Thanks for the clarifications Andrew and yes you are correct oarfish, a setup function is needed. I've added it to the example to avoid further confusion. – xolox Jun 22 '19 at 10:13
  • @JoelB: The example code in my post is written to assume that your `__init__` method has a nonempty docstring. Does it? – xolox Feb 12 '20 at 12:51
1

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
banderlog013
  • 2,207
  • 24
  • 33
0

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)
letmaik
  • 3,348
  • 1
  • 36
  • 43