4 ms·
Because a switch can usually be replaced by a dictionary? { 1: runOne, 2: runTwo, 3:runThree }[n]() is equivalent to switch(n) { case 1: run
by icebraining 15y ago
Because a switch can usually be replaced by a dictionary?
{ 1: runOne, 2: runTwo, 3:runThree }[n]()
is equivalent to
switch(n) {
case 1: runOne(); break;
case 2: runTwo(); break;
case 3: runThree(); break;
}
- DanielRibeiro 15y agoAlso, on Smalltalk (which influenced python) there is no switch statement as well. On the other hand, Smalltalk has no if, while, for statements as well (they are all methods).
- gecko 15y agoWhile Smalltalk doesn't have case statements, a) it's trivial to add them, and b) the way you get around it is totally different: rather than use a Dictionary, you instead generally make a pile of tiny classes, each with a fooBar: method, and then simply make sure you've got the right object type and call fooBar: on it indiscriminately--in other words, basically your classic visitor pattern. That's totally possible in Python, too, but I don't really ever see it done.
- datashaman 15y agoI like to use defaultdict for this. A strategy dictionary, with a default strategy. dispatch = defaultdict(default_stategy) dispatch['one'] = new_strategy print dispatch['two'] => default_strategy. Beats case statements and elif chains.
- zeekay 15y agoI usually just provide a default argument to get: dispatch.get('two', default_strategy)
- adobriyan 15y agoThis forces programmer to invent dummy names. And Python doesn't support nontrivial lambdas.
- mhb 15y agoI've seen the argument about why that's more "pythonic", but it's not compelling. Allowing some syntactic sugar would make the meaning a lot more obvious.
- jronkone 15y agoConsing for control-flow is not normal, but on Python it is. Python - not even once.