[Python-Dev] School IIb?

Guido van Rossum guido at python.org
Wed Jun 28 16:33:12 CEST 2006

On 6/28/06, Fredrik Lundh <fredrik at pythonware.com> wrote:
> Phillip J. Eby wrote:
> > Hear, hear!  We already have if/elif, we don't need another way to spell
> > it.  The whole point of switch is that it asserts that exactly *one* case
> > is supposed to match
> that's not true for all programming languages that has a switch construct, though;
> the common trait is that you're dispatching on a single value, not necessarily that
> there cannot be potentially overlapping case conditions.

You have a point.

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). Now 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.

Yet, 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, and that must have bitten many of us
(usually due to a copy-and-paste error)...

This doesn't move me to school I. But I do want to introduce school
IIb which resolves redundant cases by saying the first match wins.
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.)

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list