Quick Reference from module doc strings.

Ron Adam rrr at ronadam.com
Sat May 14 11:45:38 EDT 2005


Does anyone have suggestions on how to improve this further?


Cheers,
Ron_Adam



def getobjs(object, dlist=[], lvl=0, maxlevel=1):
     """ Retrieve 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 module before calling in most cases.
     print quick_ref('__builtins__')








More information about the Python-list mailing list