Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Sphinx Respect Importing Classes Into Package with __init__.py

I have a package:

  • foo
    • foo.py
    • bar.py
    • __init__.py

foo.py has a class Foo. In __init__.py I import class Foo so users can do:

from foo import Foo

Sphinx rightly documents Foo as foo.foo.Foo, which is right but confusing to users. How do I get Sphinx to document it as foo.Foo?

It's also important to get the overall module documentation associated with the right module.

Sphinx documents something called:

..module:: module.name

but when I use it in the first comment in a foo.py file, the doc is still attributed to foo.foo.

like image 439
Aaron Avatar asked Feb 28 '14 13:02

Aaron


2 Answers

Refer this answer for a solution.

In your case, modify your __init__.py file to:

# This lets you use foo.foo.Foo as foo.Foo in your code.
from .foo import Foo

# This lets Sphinx know you want to document foo.foo.Foo as foo.Foo.
__all__ = ['Foo']
like image 145
Nikhil Kumar Avatar answered Oct 18 '22 23:10

Nikhil Kumar


The value of the __module__ attribute is the name of the module in which a class/function/method was defined (see https://docs.python.org/2.7/reference/datamodel.html). The attribute is writable so it can be redefined in __init__.py:

Foo.__module__ = "foo"

Now if you use .. automodule:: foo, the qualified name of the Foo class will be shown as foo.Foo in the generated module documentation.


As an alternative to __module__-fiddling, you can use autoclass instead of automodule.

.. autoclass:: foo.Foo will produce the wanted output.

like image 31
mzjn Avatar answered Oct 18 '22 21:10

mzjn