[Python-Dev] switch-based programming in Python
Martin v. Loewis
martin@v.loewis.de
Thu, 8 Nov 2001 10:12:37 +0100
> > That won't work. You cannot know what type "x" has, so you don't know
> > in advance how "x == 'one'" is evaluated.
>
> But you do know that x won't change from one compare to the next,
> so a single dictionary lookup could replace the equality tests
> (provided that x is hashable).
How do you know x won't change? I certainly can write a class where it
does.
The key issue is that x must be hashable. If it is (including the
constraint that a==b implies hash(a)==hash(b)), then I agree that this
transformation would work.
> What do you think about the general idea, BTW ?
I'm also uncertain that this would give any speed-up. I assume you
want to generate a dictionary {rhs-string : byte-code-address} or the
like. I'm not convinced that the dictionary lookup + computed goto is
necessarily faster than the compare sequence; this could be
established only by implementing it (you don't need to implement
the parser/compiler aspects, just the changes to ceval.c).
There are also some security aspects here: I assume you'll put the
dictionary into the constant pool (co_consts). Of course, a dictionary
is not const, so somebody may change the dictionary, thus letting you
jump to code positions which were not intended as jump targets.
Finally, I guess tools analysing byte code will be confused.
So I'm -1 on it until I see that it actually does any good. Then I'm
-0 until I see that it does that good in real-life applications (of
course, your application would be one, but I'd like to see a second
one :-)
Regards,
Martin