Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Pythonic" equivalent for handling switch and multiple string compares

Alright, so my title sucked. An example works better:

input = 'check yahoo.com'

I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it:

if len(input) > 0:
    a = input.split(' ')
    if a[0] == 'check':
        if len(a) > 1:
            do_check(a[1])
    elif a[0] == 'search':
        if len(a) > 1:
            do_search(a[1])

I like Python because it makes normally complicated things into rather simple things. I'm not too experienced with it, and I am fairly sure there's a much better way to do these things... some way more pythonic. I've seen some examples of people replacing switch statements with dicts and lambda functions, while other people simply recommended if..else nests.

like image 721
Tom Avatar asked Mar 13 '09 04:03

Tom


1 Answers

dispatch = {
  'check': do_check,
  'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
    dispatch[cmd](arg)
else:
    do_default(cmd, arg)
like image 112
Markus Jarderot Avatar answered Oct 07 '22 04:10

Markus Jarderot