const objects (was Re: Death to tuples!)

Christopher Subich csubich.spam.block at spam.subich.block.com
Wed Dec 14 10:42:24 EST 2005


Gabriel Zachmann wrote:
> 
> I was wondering why python doesn't contain a way to make things "const"?
> 
> If it were possible to "declare" variables at the time they are bound to 
> objects that they should not allow modification of the object, then we 
> would have a concept _orthogonal_ to data types themselves and, as a 
> by-product, a way to declare tuples as constant lists.
.
.
.
> It seems to me that implementing that feature would be fairly easy.
> All that would be needed is a flag with each variable.

Nope, that's not all you need; in fact, your definition of 'const' 
conflates two sorts of constants.

Consider:

 >>>const l = 1
 >>>l = 2 # error?

And
 >>>const l = []
 >>>l.append(foo) # error?

with its more general:
 >>>const foo = MyClass()
 >>>foo.myMethod() # error?  myMethod might mutate.

And none of this can prevent:
 >>>d = {}
 >>>const foo=[d]
 >>>d['bar']='baz'

The first "constant" is the only well-defined one in Python: a constant 
name.  A "constant" name would prohibit rebinding of the name for the 
scope of the name.  Of course, it can't prevent whatsoever mutation of 
the object which is referenced by the name.

Conceptually, a constant name would be possible in a python-like 
language, but it would require significant change to the language to 
implement; possibly something along the lines of name/attribute 
unification (because with properties it's possible to have 
nearly-constant[1] attributes on class instances).

The other form of constant, that of a frozen object, is difficult 
(probably impossible) to do for a general object: without knowing ahead 
of time the effects of any method invocation, it is very difficult to 
know whether the object will be mutated.  Combine this with exec/eval 
(as the most absurd level of generality), and I'd argue that it is 
probably theoretically impossible.

For more limited cases, and for more limited definitions of immutable, 
and ignoring completely the effects of extremely strange code, you might 
be able to hack something together with a metaclass (or do something 
along the lines of a frozenset).  I wouldn't recommend it just for 
general use.

Really, the single best purpose of constant names/objects is for 
compiler optimization, which CPython doesn't do as-of-yet.  When it 
does, possibly through the PyPy project, constants will more likely be 
discovered automatically from analysis of running code.

[1] -- barring straight modification of __dict__



More information about the Python-list mailing list