[Python-Dev] Switch statement

M.-A. Lemburg mal at egenix.com
Fri Jun 23 19:51:03 CEST 2006

Georg Brandl wrote:
> M.-A. Lemburg wrote:
>> 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)
> There's a certain risk that the premature-optimization fraction will
> plaster every function with const declarations, but they write
> unreadable code anyway ;)
> Aside from this, there's still another point: assume you have quite a
> number of module-level string "constants" which you want to use in a switch.
> You'd have to repeat all of their names in a "const" declaration in order
> to use them this way.

If you want to use the switch-dispatch table optimization, yes.

I'm sure we could find ways to make such declarations more
user-friendly. E.g. to declare all symbols imported from a
module constant:

# Declare the name "module" constant:
const module

# Declare all references "module.<something>" constant:
const module.*

This would allow you to e.g. declare all builtins constant,
avoiding cluttering up your code with const declarations,
as in the above example.

Note that such a declaration would go beyond just the use in
a switch statement. It allows you to declare names reserved
within the scope you are defining them in and gives them
a special meaning - much like "global" does.

Indeed, with this kind of declaration you wouldn't need to
add the switch statement to benefit from the dispatch
table optimization, since the compiler could easily identify
an if-elif-else chain as being optimizable even if it uses
symbols instead of literals for the values.

Furthermore, the compiler could do other optimizations on the
const declared names, such as optimizing away global lookups
and turning them into code object constants lookups.

Marc-Andre Lemburg

Professional Python Services directly from the Source  (#1, Jun 23 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/

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

More information about the Python-Dev mailing list