python for everyday tasks
Michael Torrie
torriem at gmail.com
Wed Nov 27 13:15:16 EST 2013
On 11/27/2013 11:05 AM, Pavel Volkov wrote:
> Thanks for all those references.
> There's this statement in the first article:
>
> "Got a switch statement? The Python translation is a hash table, not a bunch
> of if-then statments. Got a bunch of if-then's that wouldn't be a switch
> statement in Java because strings are involved? It's still a hash table. "
>
> I can't figure out how would you translate a switch statement into hash table
> in general case.
The general case is an if/elif ladder. But consider:
def func1(): pass
def func2(): pass
def func3(): pass
dispatch = { 0: func1,
1: func2,
2: func3,
}
# do some calc
result = somecalc()
try:
dispatch[result]()
except KeyError:
# invalid result
That's what the article is talking about.
More information about the Python-list
mailing list