[Python-Dev] Switch statement
jcarlson at uci.edu
Tue Jun 20 23:12:04 CEST 2006
"Guido van Rossum" <guido at python.org> wrote:
> On 6/19/06, Josiah Carlson <jcarlson at uci.edu> wrote:
> > Regardless of readability (I know that readability counts), TOOWTDI. If
> > we allow somewhat arbitrary cases, then any potential speedup may be
> > thrown away (which would bother those of us who use dispatching), and we
> > essentially get a different syntax for if/elif/else. I don't know about
> > everyone else, but I'm not looking for a different syntax for
> > if/elif/else, I'm looking for fast dispatch with some reasonable syntax.
> Careful though. Even the most efficient switch can't meet all your
> dispatch needs; a switch requires that you be able to list all the
> cases statically in your source code. If that works for you, great.
> But if you need some kind of dynamic extensibility, switch will never
> cut it, and you'll have to use a dict of fuctions or the standard
> getattr(self, '_Prefix_' + name) dynamic-dispatch-without-dict
Indeed. Not all dispatch methods are solved by if/elif/else blocks,
nor would be solved by switch/case statements, especially not in the
case of subclassing. Though the subclassing case can be fixed with the
use of things like "if cur_case not in self.handles: ..." .
> Note that this is just Solution 1 from PEP 275.
Yes it is. I was describing it for those who hadn't read the PEP (there
were a few earlier in this thread).
> Remember that most things we usually *think* of as constants aren't
> recognized as such by the compiler. For example the constants used by
Right, which is one of two reasons why I'm not writing the bytecode hack
or even an AST transformation (the other being time). With the 'names
in case matches are bound at time X' semantic inside switch/case
statements, we gain more than could be offered with if/elif/else
> > One benefit to the non-syntax optimization is that it seems like it could
> > be implemented as a bytecode hack, allowing us to punt on the entire
> > discussion, and really decide on whether such a decorator should be in
> > the standard library (assuming someone is willing to write the decorator).
> I expect the scope of the optimization to be much less than you think,
> and I expect that people will waste lots of time trying to figure out
> why the optimization doesn't happen.
It depends. The simple case would offer very limited optimization, but
with a bit of help from Raymond's global binding decorator, it suddenly
becomes almost as useful as the currently being discussed switch/case
statement, offering one of the two options previously discussed for name
More information about the Python-Dev