python reduce constants at run or compile?

Tim Peters tim_one at email.msn.com
Thu Sep 7 07:31:57 CEST 2000


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

To save you the next eight steps in your Python education <wink>, the *only*
non-executable stmt in Python is "global".  Everything else (including
"class" & "def" stmts!) has a runtime component.  Arithmetic expressions in
particular are never "collapsed" at compile-time today.

In your example, yes, 44 will be subtracted from 120 at runtime, and the
result bound to the name DATALENGTH.  This is a one-time cost when loading a
module for the first time (relative to a single execution of the Python
interpreter).  Subsequent references to DATALENGTH retrieve the result (76)
directly.  If you're thinking of the C preprocessor, you're building on a
wrong model.

> next, i ask a step further. since tuples are immutable
> (as close to '"C" constant' as i can get?) is the python
> interpreter clever enough to reduce this one for me?
>
> DATARANGE = (44,120)
> DATALENGTH = DATARANGE[1] - DATARANGE[0]

Exactly the same story:  these are executed at runtime, and are one-time
costs upon initial module load.

> am i correct in believing that even if python doesn't
> reduce this down at compile time, it 'potentially could'?
> (doublechecking my understanding of tuples)

It does not; it could; it probably won't.

> if the compiler isn't taking care of these, should it?
> what are the major complexities keeping it from this?

I'd say lack of interest.  If anybody cared enough, they would have
contributed code to do this by now <wink>.  So long as you compute common
subexpressions outside the bodies of your most frequently executed loops,
the potential time savings is usually trivial.  I'll emphasize again that
there is nothing akin to "macro expansion" going on here, so no matter how
complicated or expensive a right-hand-side expression is, it gets evaluated
*only* when the line containing it is executed.

half-of-learning-python-is-forgetting-three-fourths-of-c-ly y'rs  - tim






More information about the Python-list mailing list