ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: List classes, methods and functions in a module
Submitter: Anand Pillai (other recipes)
Last Updated: 2008/04/04
Version no: 1.1
Category: Programs

 

4 stars 2 vote(s)


Description:

The recipe provides a method "describe" which takes a module as argument and describes classes, methods and functions in the module. The method/function description provides information on the function/method arguments using the inspect module.

Source: Text Source

#!/usr/bin/env python

from types import *
import inspect

def analyze_func(obj, method=False):

   if method:
       print 'Method: %s' % obj.__name__
   else:
       print 'Function: %s' % obj.__name__

   try:
       arginfo = inspect.getargspec(obj)
   except TypeError:
       return
   
   args = arginfo[0]
   argsvar = arginfo[1]

   if args:
       if args[0] == 'self':
           print '\t%s is an instance method' % obj.__name__
           args.pop(0)
       print '\tMethod Arguments: %s' % ' '.join(args)
       if arginfo[3]:
           dl = len(arginfo[3])
           al = len(args)
           defargs = args[al-dl:al]
           print 'Default arguments:',zip(defargs, arginfo[3])

   if arginfo[1]:
       print '\t Positional Args Param: %s' % arginfo[1]
   if arginfo[2]:
       print '\t Keyword Args Param: %s' % arginfo[2]


def analyze_klass(obj):

   print 'Class: %s' % obj.__name__
   for name in obj.__dict__:
       item = getattr(obj, name)
       if type(item) is MethodType:
           analyze_func(item, True)

def describe(module):
 
   print 'Module: %s' % module.__name__

   for name in dir(module):
       obj = getattr(module, name)
       if type(obj) in (ClassType, TypeType):
           analyze_klass(obj)
       elif type(obj) in (FunctionType, BuiltinFunctionType, BuiltinMethodType):
           analyze_func(obj)


if __name__ == "__main__":
   import test
   describe(test)

Discussion:

This came as a question in our local Python mailing list (BangPypers). I wrote up the above solution to provide a quick summary of a module in terms of classes, and simple method descriptions. The 'inspect' module makes this task relatively easy.

[Edit] - Added support for built-in functions/methods.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.