When I discovered there wasn't one, I was really annoyed and went digging for an explanation. The one I found was a suggestion if you are reaching for a switch statement, you're (probably) doing something wrong. This is not to impugn anyone else's approach or style and I will freely admit there are times when all you need is a switch and if/ else if/ else gets ugly, but most times I find the replacement for switch is not that but a dictionary holding a callable or similar. I recently showed this approach to a peer in PR and watching it click for her was awesome. She ripped out most of what she'd done and replaced some of our more ponderous permission checking with a dictionary of functions to apply.
I'd say the other thing I do when I wish I had a switch statement is realize I am writing code that is halfway to doing things The Right Way and refactor the block into smaller functions.
I came up with the following, and that definitely doesn't convince me.
def call_a():
pass
def call_b():
pass
def default_func():
pass
myswitch = {
"a": call_a
"b": call_b
}
myfunc = myswitch.get(x, default_func)
myfunc()
vs if x == "a":
pass
elif x == "b":
pass
else:
passNot actually a heavy Python user, but even though most languages I use regularly are more switch/case-heavy, I've never quite grasped why there's two largely interchangeable ways to do the one thing.
In higher level langues with strong, static types, the switch statement can indicate to the compiler you want to match on the type of the variable; it can do analysis then to make sure your pattern match is exhaustive.
For higher level languages, I would imagine typeguards would provide some of the desired functionality here, while being much more lightweight than a full alternative conditional syntax.
I don't see any DRY trade-offs, unless you're talking on a really micro character-count / code-golf level.
Making an example is simpler than formulating a defition :-):
case instance
when MyClass...
when MyOtherClass...
...
end
which would otherwise be: if instance.is_a?(MyClass)
...
elif instance.is_a?(MyOtherClass)
...
...
end
if you consider that this has support for many other expressions (regular expressions, ranges...), you'll see a very coincise construct for the purpose.To put it another way: when you're branching on the value of a single variable by comparing it to an enumerated set of values, the obvious way to do so is with switch/case.
Clarity of intent, much as comprehensions provide over imperative loops (even though switch is still imperative in most langauges). Though whether it's enough benefit to be warranted is another question; I think basic switch is not clearly compelling, though adding even basic smarter matching (like Ruby has long had, for instance) makes it moreso.
But Python's if/elif/else syntax is already clean enough that there's just not much clutter to remove. And C-style semantics on switch statements wouldn't be acceptable. And Python is a very dynamic language. So, in the end, you would end up with something that's generally the same line count and the same semantics as an equivalent if-statement, meaning it's would be more like semantic Splenda than semantic sugar.
There is no way in many languages to write an if using a match.
> A quick poll during my keynote presentation at PyCon 2007 shows this proposal has no popular support. I therefore reject it.
handlers = {'start' : handle_start, 'jump' : handle_jump, 'end' : handle_end, ...}
for tok, arg in tokens:
if tok not in handlers:
raise ValueError('Wrong token type, must be any of %s.' % ', '.join(handlers))
handlers[tok](arg)Thank you for the example.