Quick Reference from module doc strings.

Ron Adam rrr at ronadam.com
Sun May 15 16:30:53 EDT 2005


I think this deserves a little more of a description than I gave it 
initially.

The routine in the previous message does a little more than just print 
out __doc__ strings. It outputs a formatted alphabetical list of objects 
in a module with each objects, name, class or type, and then tries to 
determine if the doc string is part of the class or was inherited from a 
parent class.  If the object is a storage type, then it will print the 
objects contents/values giving you what they are at import time.  If the 
string or list, tuple, or dict is large, it will print just the 
beginning with '......' at the end to let you know there is more.

So what you get is a printable alphabetical quick reference guide with 
the first level class's, functions, exceptions, and attributes with the 
initial values after importing.  (You can also do this with a single 
class and get it's methods and attributes.)

Here is the first part of __builtins__ (Python 2.3) as an example.  If 
anyone has any suggestions or corrections, Please let me know.

Cheers,
_Ron Adam


----------------------------------------
__builtins__
Class:<type 'module'>

Built-in functions, exceptions, and other objects.

Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.

----------------------------------------
__builtins__.__debug__
Class:<type 'bool'>

__builtins__.__debug__=True

----------------------------------------
__builtins__.__doc__
Class:<type 'str'>

__builtins__.__doc__="""Built-in functions, exceptions, and other objects.

Noteworthy: None is the `nil' object; Ellipsis represents `...' in 
slices."""

----------------------------------------
__builtins__.__import__
Module:__builtin__
Class:<type 'builtin_function_or_method'>

__import__(name, globals, locals, fromlist) -> module

Import a module.  The globals are only used to determine the context;
they are not modified.  The locals are currently unused.  The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.

----------------------------------------
__builtins__.__name__
Class:<type 'str'>

__builtins__.__name__="__builtin__"

----------------------------------------
__builtins__.abs
Module:__builtin__
Class:<type 'builtin_function_or_method'>

abs(number) -> number

Return the absolute value of the argument.

----------------------------------------
__builtins__.apply
Module:__builtin__
Class:<type 'builtin_function_or_method'>

apply(object[, args[, kwargs]]) -> value

Call a callable object with positional arguments taken from the tuple args,
and keyword arguments taken from the optional dictionary kwargs.
Note that classes are callable, as are instances with a __call__() method.

Deprecated since release 2.3. Instead, use the extended call syntax:
     function(*args, **keywords).

----------------------------------------
__builtins__.ArithmeticError
Module:exceptions
Type:<type 'classobj'>

Base class for arithmetic errors.

----------------------------------------
__builtins__.AssertionError
Module:exceptions
Type:<type 'classobj'>

Assertion failed.

----------------------------------------
__builtins__.AttributeError
Module:exceptions
Type:<type 'classobj'>

Attribute not found.

----------------------------------------
__builtins__.basestring
Module:__builtin__
Class:<type 'type'>

Type basestring cannot be instantiated; it is the base for str and unicode.

----------------------------------------
__builtins__.bool
Module:__builtin__
Class:<type 'type'>

bool(x) -> bool

Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.

----------------------------------------
__builtins__.buffer
Module:__builtin__
Class:<type 'type'>

buffer(object [, offset[, size]])

Create a new buffer object which references the given object.
The buffer will reference a slice of the target object from the
start of the object (or at the specified offset). The slice will
extend to the end of the target object (or with the specified size).

----------------------------------------
Continued.....




And here is the program again.



def getobjs(object, dlist=[], lvl=0, maxlevel=1):
     """ Retreive a list of sub objects from an object. """
     if object not in dlist:
         dlist.append(object)
     if lvl<maxlevel:
         dobj = dir(eval(object))
         for item in dobj:
             try:
                 dlist = getobjs(object+'.'+item, dlist, lvl+1)
             except:
                 pass
     return dlist

def printdoc(objectlist):
     """ Return a sorted printable quick reference
         guide from a list of objects. """
     outtext = []
     objectlist.sort(lambda x, y: cmp(x.lower(), y.lower()))
     for obj in objectlist:
         object = eval(obj)
         object_type = type(object)
         outtext.append('-'*40+'\n')
         outtext.append(str(obj)+'\n')
         if hasattr(object, '__module__'):
             outtext.append("Module:"+str(object.__module__)+'\n')
         if hasattr( object,'__class__'):
             outtext.append("Class:"+str(object.__class__)+'\n\n')
         else:
             outtext.append("Type:"+str(object_type)+'\n\n')
         if isinstance(object,str):
             if len(object)>200:
                 s = object[0:200]+"......"
             else:
                 s = object
             outtext.append(obj+'=')
             if '\n' in s: quotes='"""'
             else: quotes ='"'
             if len(s)>60: print
             outtext.append(quotes+s+quotes+'\n\n')
         elif (isinstance(object,str)
                 or isinstance(object,int)
                 or isinstance(object,bool)
                 or isinstance(object,tuple)
                 or isinstance(object,list)
                 or isinstance(object,dict)):
             s = str(object)
             if len(s)<200:
                 outtext.append(obj+'='+s+'\n\n')
             else:
                 outtext.append(obj+'='+s[0:200]+'......\n\n')
         if hasattr(object,'__doc__'):
             if object.__doc__ != type(object).__doc__:
                 outtext.append(str(object.__doc__)+'\n\n')
     return ''.join(outtext)

def quick_ref(name):
     """
     quick_ref(module_name) -> printable string

     Generate a sorted quick reference guide from an objects
     doc strings.  The module_name is a string with the name of
     the module or class to get documents string from.

     Example:
         import os
         print quick_ref('os')
     """
     objlist = getobjs(name)
     return printdoc(objlist)

if __name__ == "__main__":
     #import os
     print quick_ref('__builtins__')







More information about the Python-list mailing list