Feb 20, 2011

Dictionary of Methods/Functions (Python)

Construct a dictionary with String (or other) keys and unbound methods or functions as values. During execution, use the string keys to select which method or function to execute. Can be used for simple parsing of tokens from a file thru a kind of object-oriented case statement.


import string
def function1():
print "called function 1"

def function2():
print "called function 2"

def function3():
print "called function 3"

tokenDict = {"cat":function1, "dog":function2, "bear":function3}


# simulate, say, lines read from a file
lines = ["cat","bear","cat","dog"]
for line in lines:
    # lookup the function to call for each line
    functionToCall = tokenDict[line]
    # and call it
    functionToCall()

It's embarrasingly simple really, but I use it a whole lot. Instead of functions, methods might also be used (self.method1), remember to follow the binding rules if you use methods directly from classes.

You can also pass in any attributes (including those read from a file) to the functions you call. The possibilities are pretty diverse.

I primarily use this in places where in other languages I might want a case statement. I also use it to provide a poor man's way to parse command files (say an X10 macro control file).

source
the general idea and concept from matias

No comments: