[Python-Dev] Switch statement

M.-A. Lemburg mal at egenix.com
Thu Jun 22 20:54:18 CEST 2006


Guido van Rossum wrote:
> Without const declarations none of this can work and
> the "at-function-definition-time" freezing is the best, because most
> predictable, approach IMO.

I you like this approach best, then how about using the same
approach as we have for function default argument values:

Variables which are to be regarded as constant within the
scope of the function are declared as such by using a "const"
declaration (much like we already have with the
global declaration).

a,b,c,d = range(4)
defvalue = 1

def switch(x=defvalue):
    const a,b,c,d
    switch x:
        case a: return 'foo'
        case b: return 'foo'
        case c: return 'foo'
        case d: return 'foo'
        else: raise ValueError(x)

This declaration would cause the compiler to generate
LOAD_NAME opcodes just like for defvalue which then gets
executed at code object execution time, ie. when the
function is created.

This would also work out for the solution 1 case
in the PEP (if-elif-else)... <hint><hint> :-)

def switch(x=defvalue):
    const a,b,c,d
    if x == a: return 'foo'
    elif x == b: return 'bar'
    elif x == c: return 'baz'
    elif x == d: return 'bazbar'
    else: raise ValueError(x)

Furthermore, the compiler could protect the constant
names from assignments (much in the same way it
applies special treatment to variables declared global
in a scope).

A nice side-effect would be that could easily use the
same approach to replace the often used default-argument-hack,
e.g.

def fraction(x, int=int, float=float):
    return float(x) - int(x)

This would then read:

def fraction(x):
    const int, float
    return float(x) - int(x)

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jun 22 2006)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________
2006-07-03: EuroPython 2006, CERN, Switzerland              10 days left

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::


More information about the Python-Dev mailing list