python reduce constants at run or compile?

Greg Ewing see at my.signature
Thu Sep 7 05:38:24 CEST 2000


Pete Shinners wrote:
> 
> DATALENGTH = 120-44
> 
> does the "120-44" get computed to 76 at compile time, or is
> the value computed at runtime?

At runtime. However, keep in mind that if it's at
the top level of a module, it's computed once when
the module is loaded, which is almost as good.

> DATARANGE = (44,120)
> DATALENGTH = DATARANGE[1] - DATARANGE[0]
> 
> am i correct in believing that even if python doesn't
> reduce this down at compile time, it 'potentially could'?
> what are the major complexities keeping it from this?

A great many things. The current compiler is an amazingly
simple-minded beast - it has no idea of the types of
objects being manipulated by the code it's compiling.
It doesn't even have a proper symbol table.

To do constant folding within a single expression, it
would have to keep track of the types and values of
operands, and know about all the operations on builtin
types. To do it between expressions, as in your second
example, it would need to keep a symbol table, and do
flow control to detect when a previously assigned constant
might have been invalidated by executing other code.
Etc. etc. etc.

If Python ever gets type declarations, the compiler will
need to have all this stuff and more, and then constant
folding could likely be done at little or no extra
cost. But until then, it's just not practical.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list