[Python-Dev] Simple Switch statement

Raymond Hettinger rhettinger at ewtllc.com
Mon Jun 26 17:46:09 CEST 2006

Michael Urman wrote:

> I'm trying to find some real world examples of a pygame event loop
>that really show the benefit of supporting named constants and
>expressions. I may mess up irrelevant details, but the primary case
>looks something like the following (perhaps Pete Shinners could point
>us to a good example loop online somewhere):
>    for event in pygame.event.get():
>        if event.type == pygame.KEYDOWN: ...
>        elif event.type == pygame.KEYUP: ...
>        elif event.type == pygame.QUIT: ...
>Here all the event types are integers, but are clearly meaningless as
>integers instead of an enumeration. I'd be sorely disappointed with
>the addition of a switch statement that couldn't support this as
>something like the following:
>    for event in pygame.event.get():
>        switch event.type:
>        case pygame.KEYDOWN: ...
>        case pygame.KEYUP: ...
>        case pygame.QUIT: ...
With the simplified proposal, this would be coded with an inverse mapping:

    for event in pygame.event.get():
        switch eventmap[event.type]:
        case 'KEYDOWN': ...
        case 'KEYUP': ...
        case 'QUIT': ...

Hopefully, the static() proposal will work-out and the mapping won't be 
necessary.  If it does work-out, you'll also get more error-checking 
than you get with either the if-elif version or the simplified switch-case.

>I also would like to see a way to use 'is' instead of (or inaddition
>to) '==' for the comparison, but I don't have any use cases behind

If speed is the goal, this isn't necessary.  The internal equality check 
takes a shortcut in the event of an identity match.

OTOH, if the goal is having several distinct cases that are equal but 
not identical, then that's another story.  I suggest leave the initial 
switch syntax as simple as possible and just switch on id(object).


More information about the Python-Dev mailing list