python reduce constants at run or compile?

Delaney, Timothy tdelaney at avaya.com
Thu Sep 7 06:11:43 CEST 2000


Okay - there one thing here which could be easily reduced at "compile-time",
and one which is more difficult

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

Absolute constants like this can be trivially computed/reduced at compile
time. However, this is a fairly rare circumstance, and I don't think the
compiler should be made more complex just to handle it. This type of thing
should never be placed into code which is going to be run more than once in
a session i.e. it should be at the module level so it is computed at module
load time.

The complexity would be in determining exactly *which* expressions could be
reduced. For example:

DATALENGTH = (120 - a) * 44 - 5 + 2 / b - 4

which translates to

((120 - a) * 44) - 5 + (2 / b) - 4

which in this case cannot be reduced at all, even though we have many
adjacent constants which possibly could be.

> At runtime. However, keep in mind that if it's at
> 
> > DATARANGE = (44,120)
> > DATALENGTH = DATARANGE[1] - DATARANGE[0]

This one is non-trivial. Whilst it is obvious to *me* that this is only
dealing with constants, it is not obvious to the compiler. A tuple can hold
any type of objects. Likewise, DATARANGE can refer to any type of object.
Whilst it's a perverted example, which should never happen if you are
careful, what if you are using multi-threading, and the following scenario
occurs ...

Thread 1: DATARANGE = (44,120)
<context switch to thread 2>
Thread 2: DATARANGE = (0,1)
<context switch to thread 1>
Thread 1: DATALENGTH = DATARANGE[1] - DATARANGE[0]

DATALENGTH is now equal to 1, not 76 as expected.




More information about the Python-list mailing list