Not the main point but if the if-else pattern gets tedious why is there no switch in Python?
{ 1: runOne, 2: runTwo, 3:runThree }[n]()
is equivalent to switch(n) {
case 1: runOne(); break;
case 2: runTwo(); break;
case 3: runThree(); break;
}That's totally possible in Python, too, but I don't really ever see it done.
dispatch = defaultdict(default_stategy)
dispatch['one'] = new_strategy
print dispatch['two'] => default_strategy.
Beats case statements and elif chains.
dispatch.get('two', default_strategy)
In general though, I have no idea why Python doesn't have a switch or case statement of some sort.
case [typeof(X) for x in X] of:
[int, int]:
...
[int, float]:
... { (int, int): methodWithTwoInts,
(int, float): methodsWithIntAndFloat,
...
}[ tuple([typeof(x) for x in X]) ]()Some advanced dispatch code can notice that some tuples are dispatched more often that the rest and can check for them first.
Ditto for dict lookup.
But this would unexpected for switch code.
>>> def first():
... print "a"
...
>>> def second():
... print "beta"
...
>>> caseof = {1: first, 2: second}
>>> caseof[1]()
a
>>> caseof[2]()
beta
>>>But my opinion is that it wouldn't hurt to have it there.