Search code examples
pythonpython-sphinxautodoc

Sphinx includes private attributes even though not instructed to


I did not include the :private-members: option anywhere, but Sphinx still includes private attributes in the docs for the class. What am I doing wrong?

MWE:

mypackage/foo.py:

class MyClass(object):
    """A class.

    Attributes
    ----------
    attr1 : float
        Attribute 1.
    attr2 : float
        Attribute 2.
    _private1 : float
        Private attribute 1.
    _private2 : float
        Private attribute 2.
    """
    pass

index.rst:

.. toctree::
    :maxdepth: 2
    :caption: Table of Contents

    foo

foo.rst:

``foo`` Module
==============

.. automodule:: mypackage.foo
    :members:

conf.py:

# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.

import os
import sys
sys.path.insert(0, os.path.abspath('../'))

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
]

source_suffix = '.rst'

master_doc = 'index'

language = 'en'

Rendered html:

enter image description here


Solution

  • The absence of :private-members: only takes effect for members that sphinx finds by parsing the Python code. For example:

    class MyClass(object):
        """A class"""
        attr1 = 42  #: Attribute 1.
        attr2 = 43  #: Attribute 2.
        _private1 = 44  #: Private attribute 1.
        _private2 = 45  #: Private attribute 2.
    

    In this case, it won't document _private1 and _private2 (without :private-members:).

    In you case, however, _private1 and _private2 are just text inside a doc string. I doubt even that sphinx in that case knows that they are attributes of the class.