I am trying to document a python package with sphinx
and have successfully generated html files. The package I am documenting consists of a set of *.py
files, most containing one class with a couple of files being genuine modules with functions defined. I do not need to expose the fact that each class is in a module so I have added suitable from
statements in the __init__.py
file e.g.
from base import Base
so that the user can use the import pkg
command and does not then have to specify the module that contains the class:
import pkg
class MyBase(pkg.Base): # instead of pkg.base.Base ...
...
The problem is that sphinx insists on documenting the class as pkg.base.Base
. I have tried to set the add_module_names = False
in conf.py
. However this results in sphinx showing the class as simply Base
instead of pkg.Base
. Additionally this also ruins the documentation of the couple of *.py
files that are modules.
How do I make sphinx
show a class as pkg.Base
?
And how do I set the add_module_names
directive selectively for each *.py
file?
A module can have zero or one or multiple classes. A class can be implemented in one or more . py files (modules). But often, we can organize a set of variables and functions into a class definition or just simply put them in a .
Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.
Python Module is essentially a python script file that can contain variables, functions, and classes.
Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.
Here is a way to accomplish what the OP asks for:
Add an __all__
list in pkg/__init__.py
:
from base import Base # Or use 'from base import *'
__all__ = ["Base"]
Use .. automodule:: pkg
in the .rst file.
Sphinx will now output documentation where the class name is shown as pkg.Base
instead of pkg.base.Base
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With