Created
February 21, 2010 21:56
-
-
Save rwilcox/310571 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A Sub command dispatcher for methods in Python | |
# Thanks to dectools: http://pypi.python.org/pypi/dectools | |
# | |
# Use Case: You have a function that takes 1 + N parameters. The first | |
# parameter you would use as a switch statement (in C), or as a key in | |
# a Dictionary (in Python) to figure out another function to send | |
# the other N args to. | |
# | |
# for example, command line parsers: | |
# def handle_commands(): | |
# command = sys.argv[1] | |
# params = sys.argv[1:] | |
# dispatchDict = dict("hello": say_hello) | |
# dispatchDict[command](params) | |
# | |
# BORING!! | |
# | |
# With @subcommand_dispatch we can define functions based on our expected user input | |
# triggered off the name of the function the calling code THOUGHT it was calling | |
# | |
# def handle_commands_hello(args): | |
# print "hello!" | |
# | |
# @ subcommand_dispatch | |
# def handle_commands(name, args): | |
# pass | |
# | |
# Which is easy! | |
from dectools import dectools | |
@dectools.make_call_instead | |
def subcommand_dispatch(function, args, kwargs): | |
#print "called for %s" % function.__name__ | |
fname = function.__name__ | |
name, other = args | |
try: | |
fObj = globals()[ fname +"_" +args[0] ] | |
fObj( other ) | |
except KeyError: | |
print "could not do '%s %s %s' (did you spell it right?)" % ( fname, args[0], " ".join( args[1:] ) ) | |
#print "do paver help %s to get help" | |
# Use it like: | |
def dispatcher_hello(option): | |
print "hello, " + option | |
@subcommand_dispatch | |
def dispatcher(option1, option2): | |
pass | |
print "starting the magic of subcommand_dispatch" | |
print "------------------------------------------" | |
dispatcher("hello", "bob") | |
print "------------------------------------------" | |
print "ok, all done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment