Saturday, February 1, 2014

python: using dictionaries instead of case statements

Switch Statements in Python

response, data = somefunc()
if response == "this":
    do_this_with(data)
elif response == "that":
    do_that_with(data)
elif response == "huh":
    duh(data)
# lots more elifs.
else:
    prevent_horrible_crash(data)


Replace with 

maps-as-switch.py

response_map = {"this": do_this_with,
                "that": do_that_with,
                "huh": duh}
response_map.get(response, prevent_horrible_crash)(data)