Luisa
Luisa

Reputation: 43

Using pydoc on modules with imported functions

I have created my own module X. At the beginning, I import functions from some other modules (e.g. from math import func). I have noticed that when I create documentation with:

pydoc -w X

the resulting file also contains the imported function function from the math module, which is undesirable (especially if I import many functions from several modules, which is what I do).

It can be avoided by instead calling:

import math

but in this case I have to import all the functions and then call them using math.func instead of just func.

Is there another way with which I can avoid populating my documentation with imported functions while still being able to import functions with from?

Upvotes: 4

Views: 2119

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

Looking inside the source for Pydoc you can see the following comment made:

if all is not None:
     # only document that which the programmer exported in __all__
     return name in all

meaning that pydoc will look for the __all__ module attribute, and, if defined, will only document the functions defined in it.

So, for you module X, you can define the functions to be exported in __all__ by specifying their names. Only those will get documented in the corresponding Functions section:

__all__ = ['myfunc1', 'myfunc2', ..., 'myfuncN']

Case in point:

Without __all__, the following simple file named mod.py:

from math import cos

def myfunc():
    """ documentation"""
    pass

Generates a mod.html file that contains the documentation for the user defined myfunc() and for the imported built-in function cos():

                enter image description here

By adding __all__ and specifying the function name(s) you'd want to export inside it:

__all__ = ['myfunc']  # visible names
from math import cos

def myfunc():
    """ documentation"""
    pass

You'll 'filter out' the cos() function and only have documentation for myfunc():

                      enter image description here


Note: __all__ can contain functions and variable names used inside you script. pydoc will discriminate between these and segregate them in two different groups:

  1. Functions in Functions
  2. Variables in Data.

Upvotes: 6

Related Questions