Immutable instances, constant values

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Nov 19 20:51:25 EST 2005


On Sun, 20 Nov 2005 08:56:33 +1100, Ben Finney wrote:

> Steven D'Aprano <steve at removethiscyber.com.au> wrote:
>> On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote:
>> > Is there any difference between a Python immutable value, and a
>> > constant? I suppose "constant" also implies that the *name* binds
>> > unchangeably to a particular value. Is that meaningful?
>> 
>> That's precisely how I understand "constant" to be useful.
> 
> The Python docs don't really talk about such a thing. However, the
> None name cannot be re-bound. Is that all that's required to have a
> "constant" in Python?

I think None is a special case. The docs have said that None will become
a keyword in the future.

> If so, it's part of the assignment statement, and not something the
> object itself can decide. True?

Yes, that would be how I interpret constants: You want a name which can't
be re-bound to something else.

One work-around is to use the convention of writing the name in all caps:

CONSTANT = some_value

and then trust that your module user doesn't rebind CONSTANT. I'd like to
see support for something a little stronger than just "cross your fingers
and hope", without necessarily going all the way to Pascal's full
enforcement of constants. "We're all adults here" -- if somebody *really*
wants to rebind CONSTANT, I'm not going to stop them, but I want them to
jump through a hoop to do it, as a reminder that the module creator thinks
they shouldn't be doing it.

The obvious analogy is with name mangling of __private attributes in
classes. 


>> > How does one actually ensure an object is immutable? Is it a matter
>> > of overriding a bunch of methods, or is ther a neater way?
> 
> Really hoping someone can come up with an answer for this.

So am I :-)

Have you looked at the source for Frozenset? It was a pure Python module
in Python 2.3, before becoming a built-in in 2.4.



-- 
Steven.




More information about the Python-list mailing list