3

There are several questions here about showing private methods using Autodoc, but I've not seen anything about showing only private methods.

Private methods and regular methods can be shown as follows:

.. autoclass:: my_package.my_file.MyClass
   :members:
   :private-members:

However, removing :members: causes none of the methods to be displayed.

How can I show just the private methods, and just for this one directive?

snazzybouche
  • 2,241
  • 3
  • 21
  • 51
  • would make much more sens that :private-members: just add the :private-members: – G M Dec 10 '22 at 13:07

1 Answers1

2

Found a way!

Using the Skipping Members setting detailed here, I was able to define a rule to selectively skip members.

In conf.py:

def hide_non_private(app, what, name, obj, skip, options):
    # if private-members is set, show only private members
    if 'private-members' in options and not name.startswith('_'):
        # skip public methods
        return True
    else:
        # do not modify skip - private methods will be shown
        return None

def setup(app):
    app.connect('autodoc-skip-member', hide_non_private)

Whenever autodoc has to decide whether or not to include a member in documentation (which it does whenever a the subject of a directive contains that member), this function is called. The function returns a bool representing whether or not this member should be skipped. If True, it doesn't appear. If False, it does. If None, then the result of this function is ignored and the next skip-checking method is called.

If the directive contains the option :private-members: and the member name does not start with _ (i.e. it's a public method), it is skipped and will not appear on the documentation.

So when I generate documentation using:

.. autoclass:: my_package.my_file.MyClass
   :members:
   :private-members:

The public methods are not shown, and the private methods are.

I still need to set :members:, though, otherwise this check doesn't even happen in the first place. If I find somewhere where I do actually need to list both public and private methods, I'll need to find some more sophisticated check.

snazzybouche
  • 2,241
  • 3
  • 21
  • 51