We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Idea: Switch Statement

Fredrik Lundh | June 2006

The switch/case statement is a variant of if/elif, which evaluates the controlling expression once, and provides a more convenient syntax for the subtests.

switch expression [as target] :
case [in] expression:
    suite

[else:
    suite ]

The case expressions are evaluated in order, until a matching expression is found. The case form corresponds to an == test. The case in form corresponds to an in test.

The switch statement has the same behaviour as a corresponding if statement. In other words:

     switch EXPR as VAR:
     case E1:
         ...
     case in E2:
         ...
     else:
         ...

is the same thing as:

     VAR = EXPR
     if VAR == E1:
         ...
     elif VAR in E2:
         ...
     else:
         ...

If the as clause is omitted, an internal variable is used instead.

Examples

In its simplest form, the switch statement is just sugar for a standard if/elif statement:

    def func(value):
        switch value:
        case 1:
            ...
        case 2:
            ...

is the same thing as:

    def func(value):
        if value == 1:
            ...
        elif value == 2:
            ...

However, if you replace value with an arbitrary expression, the switch form will only evaluate the expression once.

The as clause can be used to capture the result of the expression, for later use (either in cases or in suites):

    def func(value):
        switch expression as var:
        case 2:
            print "bike"
        case 4:
            print "car"
        else:
            print var, "was unexpected"

The static expression form (see this page) can be used to provide hints to the compiler:

    def func(value):
        switch value:
        case static foo.bar:
            ...
        case static foo.fie:
            ...
        case static foo.fum:
            ...

Here, the runtime may replace the repeated tests with a single table (or dictionary) lookup.

References

See the current python-dev thread titled Switch statement.