[Python-Dev] Simple Switch statement
murman at gmail.com
Tue Jun 27 01:26:45 CEST 2006
On 6/26/06, Raymond Hettinger <rhettinger at ewtllc.com> wrote:
> 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': ...
Ah, here's where it gets interesting. While that definitely works on
the surface, it can run into some difficulties of scope. SDL (on which
pygame is based) allows user-defined events, also integers, but
without a predefined meaning. If pygame provides the inverse mapping,
it won't contain the user-defined events. If you construct it, you
have to choose between a local lookup and a global one, and then we
start seeing a global store for an essentially local construct, or we
risk differences when there's more than one locality for using it.
While you're right; it should be simple to ensure that the inverse map
handles at least the set the switch handles, and it keeps evaluation
simpler, I still find the limitation ugly. As mentioned, the early
error checking is poor, and it just doesn't feel like the rest of
> >I also would like to see a way to use 'is' [...]for the comparison
> [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).
Switching on id(object) only sounds palatable if we're not bound by
the simple switch's limitations. Having a second (if inverted) mapping
merely of identifier to object smells particularly rancid.
What if I want some cases done as identity, but some as equality?
Since I'm having no luck finding a real use case for this, perhaps I
should assume a nested switch would be adequate. Assuming static or
capture it doesn't look too bad, so I think I'll go with Guido's
hypothesis that it's a red herring.
case id(object): ...
case id(None): ...
case 1: ...
else: raise ValueError
Michael Urman http://www.tortall.net/mu/blog
More information about the Python-Dev