How to use Sphinx's autodoc to document a class's __init__(self) method?

Jacob Marble picture Jacob Marble · Apr 8, 2011 · Viewed 41.5k times · Source

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'

Answer

mzjn picture mzjn · Apr 8, 2011

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