From 85a099ca3e6037c612c44ac131ab5e7ff50e2ab8 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Wed, 28 Jun 2006 14:41:23 +0000 Subject: [PATCH] Introducing school IIb -- duplicate cases resolved by case order, not errors. --- pep-3103.txt | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/pep-3103.txt b/pep-3103.txt index 36718c3b0..000171960 100644 --- a/pep-3103.txt +++ b/pep-3103.txt @@ -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 --------------------------------