[Python-Dev] Simple Switch statement

Raymond Hettinger rhettinger at ewtllc.com
Sun Jun 25 22:37:22 CEST 2006

>>No thanks.  That is its own can of worms.  The obvious solutions (like const
>>declarations, macros, or a syntax to force compile-time expression 
>>are unlikely to sit well because they run afoul Python's deeply ingrained
>I think perhaps you haven't been paying close attention to Fredrik's 
Yes, I have been.  That is one of the three options I listed above.  
Each has its own issues.

The static() keyword works like Forth's brackets for forcing 
compile-time evaluation.  The issue for us is that unlike other Python 
expressions, there are inconvenient limitiations on what can be 
expressed inside:

   five = 5
   eight = [8]
   def f(x, six=6):
          seven =  7
          a = static(five + 4)    # this is legal
          b = static(six + 4)      # this is illegal
          c = static(seven + 4) # this is illegal
          d = static(eight + [4]) # this is illegal

That will be a perpetual maintenance trap and conundrum for newbies.

Besides, the issue of constantification is orthogonal to the discussion 
at hand.  If compile-time expression evaluation ever gets approved, it 
is no problem to extend my switch statement proposal to accomodate it.  
IOW, my simplified version does not preclude future buildouts for your 
constantification magic.

>  The "static" operator simply lifts expression evaluation to 
>function definition time, so that this:
>     def x(y):
>         print y * static(123+456)
>becomes equivalent to this:
>     foo = 123+456
>     def x(y):
>         print y * foo

FWIW, this is a crummy example.  Py2.5 already makes a better version of 
this transformation.

> >> def f(y):
            print y * (123+456)

> >> from dis import dis
> >> dis(f)

  2           0 LOAD_FAST                0 (y)
              3 LOAD_CONST               3 (579)
              6 BINARY_MULTIPLY    
              7 PRINT_ITEM         
              8 PRINT_NEWLINE      
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE      

>Meanwhile, you seem to be arguing that forcing the use of literals at 
>compilation time is somehow more dynamic than allowing them to be computed 
>at runtime!  I don't get it. 
You may be reading to much into it.  The essential idea that is that 
limiting case values to constants is a simplifying assumption that makes 
it easy to explain and easy to compile.  I wasn't truly happy with it 
until I started trying it on real code examples and found that it fit 
effortlessly and that the code was much improved.  Also, there was some 
appeal in knowing that if some constantification proposal gets accepted, 
then those would become allowable values also.


More information about the Python-Dev mailing list