[Python-Dev] Switch statement

Nick Coghlan ncoghlan at gmail.com
Thu Jun 15 12:37:35 CEST 2006


M.-A. Lemburg wrote:
> The standard
> 
> if ...
> elif ...
> efif ...
> else:
>     ...
> 
> scheme already provides the above logic. There's really
> no need to invent yet another syntax to write such
> constructs, IMHO.

It's a DRY thing. The construct that a switch statement can replace actually 
needs to be written:

v = ...
if v == ...:
    ...
elif v == ...:
    ...
elif v == ...:
    ...
else:
    ...

The 'v =' part is replaced by 'switch' and the 'if v ==' and 'elif v ==' are 
all replaced by 'case'.

A separate statement is also easier to document to say that order of 
evaluation of the cases is not guaranteed, and that the cases may only be 
evaluated once and cached thereafter, allowing us free rein for optimisations 
that aren't possible with a normal if statement. The optimisation of the 
if-elif case would then simply be to say that the compiler can recognise 
if-elif chains like the one above where the RHS of the comparisons are all 
hashable literals and collapse them to switch statements.

It's also worth thinking about what a 'missing else' might mean for a switch 
statement. Should it default to "else: pass" like other else clauses, or does 
it make more sense for the default behaviour to be "else: raise 
ValueError('Unexpected input to switch statement')", with an explicit "else: 
pass" required to suppress the exception?

The lack of a switch statement doesn't really bother me personally, since I 
tend to just write my state machine type code so that it works off a 
dictionary that I define elsewhere, but I can see the appeal of having one, 
*if* there are things that we can do with a separate statement to make it 
*better* for the purpose than a simple if-elif chain or a predefined function 
lookup dictionary.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list