Re:Five-minute Multimethods in Python
by candeira on Wednesday December 07, 2011 @09:53AM
(#3323968)
Python doesn't need a switch or case statement because you can write a suite of ad-hoc functions, stick them in a dictionary with your values as keys, and dispatch on the values:
>>> def first():
... print "a"
...
>>> def second():
... print "beta"
...
>>> caseof = {1: first, 2: second}
>>> caseof[1]()
a
>>> caseof[2]()
beta
>>>
Re:Five-minute Multimethods in Python
by yummyfajitas on Wednesday December 07, 2011 @09:25AM
(#3323867)
Now it's a single value:
case [typeof(X) for x in X] of:
[int, int]:
...
[int, float]:
...
Re:Five-minute Multimethods in Python
by icebraining on Wednesday December 07, 2011 @09:40AM
(#3323918)
{ (int, int): methodWithTwoInts,
(int, float): methodsWithIntAndFloat,
...
}[ tuple([typeof(x) for x in X]) ]()
Re:Five-minute Multimethods in Python
by adobriyan on Wednesday December 07, 2011 @09:49AM
(#3323956)
Actually this is better that switch (or whatever).
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.
In general though, I have no idea why Python doesn't have a switch or case statement of some sort.