[Python-Dev] Switch statement
Guido van Rossum
guido at python.org
Wed Jun 21 07:14:51 CEST 2006
On 6/20/06, Phillip J. Eby <pje at telecommunity.com> wrote:
> At 12:26 PM 6/21/2006 +1200, Greg Ewing wrote:
> >Guido van Rossum wrote:
> >
> > > But it would be easy enough to define a dict-filling function that
> > > updates only new values.
> >
> >Or evaluate the case expressions in reverse order.
>
> -1; stepping through the code in a debugger is going to be weird enough,
> what with the case statements being executed at function definition time,
> without the reverse order stuff.
Agreed.
> I'd rather make it an error to list the
> same value more than once; we can just check if the key is present before
> defining that value.
That makes sense too.
I was thinking of a use case where you'd have a couple of sets of
cases that need the same treatment per set (sre_compile.py has a few
of these) but one of the sets has an exception. With the if/elif style
you could write this as
if x is exception:
...exceptional case...
elif x in set1:
...case for set1...
elif x in set2:
..case for set2...
etc.
But the prospect of something like this passing without error:
switch x:
case 1: ...case 1...
case 1: ...another case 1?!?!...
makes me think that it's better to simply reject overlapping cases.
BTW I think the several-sets use case above is important and would
like to have syntax for it.
Earlier it was proposed to allow saying
case 1, 2, 3: ...executed if x==1 or x==2 or x==3...
but now that we're agreed to evaluate the expression at function
definition time, I want to support
case S: ...executed if x in S...
but that would be ambiguous. So, thinking aloud, here are a few possibilities:
case A: ... if x == A...
cases S: ...if x in A...
or perhaps (saving a keyword):
case A: ... if x == A...
case in S: ...if x in A...
This would also let us write cases for ranges:
case in range(10): ...if x in range(10)...
I propose that the expression used for a single-value should not allow
commas, so that one is forced to write
case (1, 2): ...if x == (1, 2)...
if you really want a case to be a tuple value, but you should be able to write
case in 1, 2: ...if x in (1, 2)...
since this really doesn't pose the same kind of ambiguity. If you
forget the 'in' it's a syntax error.
Hm, so this still doesn't help if you write
case S: ...
(where S is an immutable set or sequence) when you meant
case in S: ...
so I'm not sure if it's worth the subtleties.
Time for bed here,
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list