0

We have a module, in which each class file is in a file starting with an underscore. In the init.py, we import these files, and we expose constructor functions for each class (this is necessary as each class constructor needs some additional state that we don't want users of the module to need to bother with).

E.g. we may have _foo.py with:

class Foo(object):
  def __init(context, params):
    ...

and in init.py we have:

from ._foo import Foo as _Foo

def foo(params):
  return _Foo(_getContext(), params)

I'm trying to generate documentation with Sphinx autodoc for this. I obviously want documentation to be generated for Foo and its methods (although preferably not its constructor), as well as for the foo() constructor wrapper.

I can get Sphinx to generate docs for foo() but can't seem to get it to generate anything for Foo. I've tried:

.. automodule:: foo_module
    :members:

as well as:

.. autoclass:: foo_module.Foo
    :members:

but to no avail. The former just includes foo(); the latter gives me an error:

index.rst:17: WARNING: autodoc: failed to import class u'Foo' from module u'foo_module'; the following exception was raised:
Traceback (most recent call last):
  File "/python2.7/site-packages/sphinx/ext/autodoc.py", line 342, in import_object
    obj = self.get_attr(obj, part)
  File "/python2.7/site-packages/sphinx/ext/autodoc.py", line 241, in get_attr
    return safe_getattr(obj, name, *defargs)
  File "/python2.7/site-packages/sphinx/util/inspect.py", line 114, in safe_getattr
    raise AttributeError(name)
AttributeError: Foo

Is there a way around this?

Graham Wheeler
  • 2,734
  • 1
  • 19
  • 23
  • 1
    Try defining `__all__` to include `_Foo` – kindall Apr 07 '15 at 18:05
  • That works, but it means we do expose the Foo constructor. I guess there is no way around that, as "Foo.__init__" is not documented as a method, but rather as a class header "class Foo(context, params)". Although actually it didn't work with _Foo; I had to change init to use "from ._foo import Foo" and drop the underscore before it worked. – Graham Wheeler Apr 07 '15 at 18:38
  • 1
    Don't put an `__init__` method directly on the class; instead name it something like `_init` (assuming you're not documenting "private" members) and include `__init__ = _init` in the class. :-) – kindall Apr 07 '15 at 18:46

1 Answers1

0

Long ago, but...

Just use the directive option :private-members: as well.

From https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

red-isso
  • 305
  • 1
  • 7