Introducing school IIb -- duplicate cases resolved by case order, not errors.

This commit is contained in:
Guido van Rossum 2006-06-28 14:41:23 +00:00
parent f4ddb4ef6e
commit 85a099ca3e
1 changed files with 29 additions and 1 deletions

View File

@ -390,10 +390,38 @@ that it's right to allow dead code due to overlapping cases to occur
unflagged, when the dict-based dispatch implementation makes it so
easy to trap this.
However, there are some use cases for overlapping/duplicate cases.
Suppose you're switching on some OS-specific constants (e.g. exported
by the os module or some module like that). You have a case for each.
But on some OS, two different constants have the same value (since on
that OS they are implemented the same way -- like O_TEXT and O_BINARY
on Unix). If duplicate cases are flagged as errors, your switch
wouldn't work at all on that OS. It would be much better if you could
arrange the cases so that one case has preference over another.
There's also the (more likely) use case where you have a set of cases
to be treated the same, but one member of the set must be treated
differently. It would be convenient to put the exception in an
earlier case and be done with it.
(Yes, it seems a shame not to be able to diagnose dead code due to
accidental case duplication. Maybe that's less important, and
pychecker can deal with it? After all we don't diagnose duplicate
method definitions either.)
This suggests school IIb: like school II but redundant cases must be
resolved by choosing the first match. This is trivial to implement
when building the dispatch dict (skip keys already present).
(An alternative would be to introduce new syntax to indicate "okay to
have overlapping cases" or "ok if this case is dead code" but I find
that overkill.)
Personally, I'm in school II: I believe that the dict-based dispatch
is the one true implementation for switch statements and that we
should face the limitiations up front, so that we can reap maximal
benefits.
benefits. I'm leaning towards school IIb -- duplicate cases should be
resolved by the ordering of the cases instead of flagged as errors.
When to Freeze the Dispatch Dict
--------------------------------