Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I document classes without the module name?

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?

like image 237
Major Eccles Avatar asked Feb 27 '13 15:02

Major Eccles


People also ask

CAN module be a class?

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 .

How do you know all the names defined in a module?

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.

Can Python modules contain classes?

Python Module is essentially a python script file that can contain variables, functions, and classes.

What is __ all __ in Python?

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.


1 Answers

Here is a way to accomplish what the OP asks for:

  1. Add an __all__ list in pkg/__init__.py:

    from base import Base    # Or use 'from base import *'
    
    __all__ = ["Base"]
    
  2. 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.

like image 120
mzjn Avatar answered Sep 18 '22 20:09

mzjn