Python: How to print function details iteratively using inspect and getmembers

As described in a previous post, the help() function is great for seeing details about any given module function, one at at time.

Python: How to use the built-in help( ) and dir( ) functions

For example:

print help(imageio.mimsave)

However, sometimes we want to see details for all of the functions in an imported module. Here is one way to do this programmatically. For example, getting details about all of the functions in the imageio module:

from inspect import getmembers, isfunction

import imageio
print dir(imageio)

functions_list = [o for o in getmembers(imageio) if isfunction(o[1])]
for f in functions_list:
    print "\n-------------------------------------------\n"
    print help(f[1])
    print "\nDefined arguments:\n", f[0], f[1].__code__.co_varnames
  • Load tuples of all function names and object references into a list using getmembers and isfunction. (See line 6)
  • Iterate through the functions list. The first element of every tuple is the function name and the second element is the object reference. We can simply use help() on every object reference.
  • To generate a list of defined argument names, we can then use .__code__.co_varnames.  (Line 10 in the code example.)

Example of output:

-------------------------------------------

Help on function volwrite in module imageio.core.functions:

volwrite(uri, im, format=None, **kwargs)
    volwrite(uri, vol, format=None, **kwargs)
    
    Write a volume to the specified file.
    
    Parameters
    ----------
    uri : {str, file}
        The resource to write the image to, e.g. a filename or file object,
        see the docs for more info.
    vol : numpy.ndarray
        The image data. Must be NxMxL (or NxMxLxK if each voxel is a tuple).
    format : str
        The format to use to read the file. By default imageio selects
        the appropriate for you based on the filename and its contents.
    kwargs : ...
        Further keyword arguments are passed to the writer. See :func:`.help`
        to see what arguments are available for a particular format.

None

Defined arguments:
volwrite ('uri', 'im', 'format', 'kwargs', 'writer')

For more information, see:
https://docs.python.org/2/library/inspect.html

Leave a Reply