having both dynamic and static variables

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Mar 6 21:14:08 EST 2011


On Sun, 06 Mar 2011 12:59:55 -0800, Westley Martínez wrote:

> I'm confused. Can someone tell me if we're talking about constant as in
> 'fixed in memory' or as in 'you can't reassign' or both?

Python already has fixed in memory constants. They are immutable objects 
like strings, ints, floats, etc. Once you create a string "spam", you 
cannot modify it. This has been true about Python forever.

What Python doesn't have is constant *names*. Once you bind an object to 
a name, like this:

s = "spam"

you can't modify the *object*, but you can rebind the name:

s = "Nobody expects the Spanish Inquisition!"

and now your code that expects s to be "spam" will fail. So the only new 
feature under discussion is a way to bind-once names, which many people 
call constants.

Perhaps the name is not the best, since I'm sure some people will be 
surprised that you can do this:

# hypothetical example
const L = [1, 2, 3]
L.append(4)  # works
del L[:]  # works
L = []  # fails

but I call that a feature, not a bug. If you want an immutable constant, 
use a tuple, not a list.




-- 
Steven



More information about the Python-list mailing list