[Tutor] FunctionType list from ModuleType Attributes

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 11 Feb 2002 16:52:48 -0800 (PST)

On Tue, 12 Feb 2002, Remco Gerlich wrote:

> On  0, Fred Allen <fallen@leveltwo.com> wrote:
> > Dear Tutors,
> > 
> > I am contemplating a small program to read a module file and print the
> > module's __doc__ text (if any) and, then, print all comprised functions'
> > func_doc text.
> > 
> > My design requires I either recast a module name from ModuleType (module
> > name) to StringType or vice versa, or a FunctionType (function name) to a
> > StringType or vice versa.  I cannot seem to find means for any of these
> > operations described in the documentation.   They are surely no-brainers,
> > leaving my ego a bit rumpled.  With advance thanks for any help, I am,
> Modules have a name, stored in mod.__name__ . Try e.g.
> >>> import os
> >>> print os.__name__
> os
> >>>
> Although functions don't strictly have a name, if you need a description
> that includes the likely name (but it may be wrong), try str(f) for a
> function f.
> Easiest however would be to use a for loop over the names in
> dir(module), then you alread know what the function is called in the
> module.

The 'inspect' module might be very useful useful here: it has a few
utility functions in there to extract docstrings from all things in a


Here's an example of how 'inspect' can help:

>>> functions = inspect.getmembers(string, inspect.isfunction)
>>> docs = {}
>>> for name, object in functions: docs[name] = object.__doc__
>>> docs['strip']
'strip(s) -> string\n\n    Return a copy of the string s with leading and
trailing\n    whitespace removed.\n\n    '

Good luck to you!