[Tutor] Using dictionaries to call functione

dman dsh8290@rit.edu
Fri, 17 Aug 2001 10:40:34 -0400

On Fri, Aug 17, 2001 at 09:14:23AM -0500, Kevin McCormick wrote:
| I have seen several examples of using dictionaries to call functions.  I
| believe the function name is the dictionary key, and its values are the
| associated arguments.  Yet, I find this method difficult to understand. 
| For example, I would like to pass a list of words and parameters to a
| function, and for each word in the list, call word(parameter1,
| parameter2, ...) referenced in a dictionary which somehow calls the
| associated function (called a "dispatch table", I think).  What are the
| basic concepts of this method?

In python, functions are objects just like everything else.  This
means that they can be stored in a dictionary.  The key can be
anything you want it to be, but is often a string or integer that is
directly related to some input.  The value is just a reference to the
function.  The client would retrieve that function object from the
dictionary then call it just as it would any other function.  The only
trick is to make sure that the client knows what sort of arguments the
function expects.  Here is an example :

def func1( p1 , p2 ) :
    print "func1 called : %s , %s" % (p1 , p2)

def func2( p1 , p2 ) :
    print "func2 called : %s , %s" % (p1 , p2)

dispatch_table = {
    "hello" : func1 ,
    "bye" : func2 

if __name__ == "__main__" :
    import sys
    if not dispatch_table.has_key( sys.argv[1] ) :
        print "Unkown command '%s'" % sys.argv[1]
        sys.exit( 1 )

    if len( sys.argv ) != 4 :
        print "Not enough arguments!"
        sys.exit( 1 )

    the_func = dispatch_table[ sys.argv[1] ]
    the_func( sys.argv[2] , sys.argv[3] )

Here is a demonstration of how this script could be used :

$ ./dispatch_demo.py fubar
Unkown command 'fubar'

$ ./dispatch_demo.py hello arg1 arg2
func1 called : arg1 , arg2

$ ./dispatch_demo.py bye spam eggs
func2 called : spam , eggs