constant in python?

Alex Martelli aleaxit at
Sat Aug 18 18:59:30 CEST 2001

"Michael Ströder" <michael at> wrote in message
news:3B7E5355.675D569B at
> Alex Martelli wrote:
> >
> > > >
> >
> > If something can be done with a few lines of code in the
> > language as it is, it requires very strong motivation for that
> > something to become a built-in language mechanism:
> I would guess that the recipe above causes some performance penalty.

Why guess, when you can measure?

Say is like in the recipe, is an empty
normal module, and contains:

import time, const, normal

start = time.clock()
const.magic = 23
sum = 0L
for i in range(100000):
    sum += const.magic
stend = time.clock()

print "const : %5.2f"%(stend-start)

start = time.clock()
normal.magic = 23
sum = 0L
for i in range(100000):
    sum += normal.magic
stend = time.clock()

print "normal: %5.2f"%(stend-start)

Here are three runs on my box:

const :  1.44
normal:  1.60

const :  1.63
normal:  1.53

const :  1.41
normal:  1.53

See?  No statistically significant difference penalizes the
const module vs a normal module -- it so happens the
loop using the const module was faster two times out
of three, but this is indeed happenstance.

Moral: never guess at performance -- it often baffles the
intuition even of the most accomplished expert.  MEASURE.

> > I think that "constants" are a good
> > example of something that should NOT be in the language
> > itself, exactly because it's a minor issue and it can be
> > easily implemented without too much trouble
> Disclaimer: I'm not a compiler expert.
> IMHO constants are useful in compiled languages because they are
> immutable and therefore a compiler can insert them as "in-line"
> operands for optimization.

Sure, no doubt you can gain a microsecond or two each
time a constant is a literal rather than having to be fetched
anew from the module owning it.  But, so what?!  Any
good Python developer using a module attribute (that is
not meant to change) in a tight loop that'a performance
hot-spot would surely 'hoist' the module access out of
the loop, using a local function variable instead (which
is just as fast to access as a literal).

Don't guess -- MEASURE: change the above program to
consider literals and hoisting too: and see what comes up...

The design of the Python language is *NOT* traditionally
driven by an obsession with micro-optimizations -- thanks
be, or it would most definitely _NOT_ be Python.  These
misplaced performance-related worries surely can't justify
perverting the language by adding a built-in "constant".


More information about the Python-list mailing list