[Python-Dev] Alternatives to switch?
Greg Ewing
greg.ewing at canterbury.ac.nz
Mon Jun 26 04:44:17 CEST 2006
Talin wrote:
> def outer():
> def inner(x):
> switch(x):
> case 1: ...
> case 2: ...
> case 3: ...
>
> return inner
>
> If the switch cases are bound at the time that 'inner' is defined, it
> means that the hash table will be rebuilt each time 'outer' is called.
I was just thinking the same thing...
> But the compiler has no idea which of these two cases is true.
Actually I think it does, by looking at the scopes of
names referred to in the case expressions. Suppose
there were a rule that case expressions are evaluated
as early as possible, and in the outermost possible
scope that contains all the names that they reference.
Then, in
fred = 1
mary = 2
def f():
...
def g():
...
switch x:
case fred:
...
case mary:
the case expressions would be evaluated at the module
scope, somewhere between the binding of mary and the
definition of f().
The distinction between module and function scopes
could then go away. A case expression could reference
a local if it wanted, at the cost of the case expression
being evaulated for every call to the function. A
case at the module level would just be an instance
of that.
--
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | Carpe post meridiem! |
Christchurch, New Zealand | (I'm not a morning person.) |
greg.ewing at canterbury.ac.nz +--------------------------------------+
More information about the Python-Dev
mailing list