[Python-Dev] Making mutable objects readonly

M.-A. Lemburg mal@lemburg.com
Wed, 31 Jan 2001 18:21:02 +0100

Skip Montanaro wrote:
> What stimulated this thread about making mutable objects (temporarily)
> immutable?  Can someone give me an example where this is actually useful and
> can't be handled through some existing mechanism?  I'm definitely with
> Fredrik on this one.  Sounds like madness to me.

This thread is an offspring of the "for something in dict:" thread.
The problem we face when iterating over mutable objects is that
the underlying objects can change. By marking them read-only we can
safely iterate over their contents.

Another advantage of being able to mark mutable as read-only is
that they may become usable as dictionary keys. Optimizations such
as self-reorganizing read-only dictionaries would also become
possible (e.g. attribute dictionaries which are read-only could
calculate a second hash value to make the hashing perfect).
> I'm just guessing here, but since the most common need for immutable objects
> is a dictionary keys, I can envision having to test the lock state of a list
> or dict that someone wants to use as a key everywhere you would normally
> call has_key:
>     if l.islocked() and d.has_key(l):
>        ...
> If you want immutable dicts or lists in order to use them as dictionary
> keys, just serialize them first:
>     survey_says = {"spam": 14, "eggs": 42}
>     sl = marshal.dumps(survey_says)
>     dict[sl] = "spam"

Sure and that's what .items(), .keys() and .values() do. The idea
was to avoid the extra step of creating lists or tuples first.
> Here's another pitfall I can envision.
>     survey_says = {"spam": 14, "eggs": 42}
>     survey_says.lock()
>     dict[survey_says] = "Richard Dawson"
>     survey_says.unlock()
> At this point can I safely iterate over the keys in the dictionary or not?

Tim already pointed out that we will need two different read-only

	a) temporary
	b) permanent

For dictionaries to become usable as keys in another dictionary,
they'd have to marked permanently read-only.

Marc-Andre Lemburg
Company:                                        http://www.egenix.com/
Consulting:                                    http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/