[Python-Dev] Making mutable objects readonly

M.-A. Lemburg mal@lemburg.com
Wed, 31 Jan 2001 20:03:12 +0100

Skip Montanaro wrote:
>     MAL> This thread is an offspring of the "for something in dict:" thread.
>     MAL> The problem we face when iterating over mutable objects is that the
>     MAL> underlying objects can change. By marking them read-only we can
>     MAL> safely iterate over their contents.
> I suspect you'll find it difficult to mark dbm/bsddb/gdbm files read-only.
> (And what about Andy Dustman's cool sqldict stuff?)  If you can't extend
> this concept in a reasonable fashion to cover (most of) the other objects
> that smell like dictionaries, I think you'll just be adding needless
> complications for a feature than can't be used where it's really needed.

We are currently only talking about Python dictionaries here, even though
other objects could also benefit from this.
> I see no problem asking for the items() of an in-memory dictionary in order
> to get a predictable list to iterate over, but doing that for disk-based
> mappings would be next to impossible.  So, I'm stuck iterating over
> something can can change out from under me.  In the end, the programmer will
> still have to handle border cases specially.  Besides, even if you *could*
> lock your disk-based mapping, are you really going to do that in situations
> where its sharable (that's what databases they are there for, after all)?  I
> suspect you're going to keep the database mutable and work around any
> resulting problems.
> If you want to implement "for key in dict:", why not just have the VM call
> keys() under the covers and use that list?  It would be no worse than the
> situation today where you call "for key in dict.keys():", and with the same
> caveats.  If you're dumb enough to do that for an on-disk mapping object,
> well, you get what you asked for.

That's why iterators do a much better task here. In DB design
these are usually called cursors which the allow moving inside
large result sets. But this really is a different topic...

Readonlyness could be put to some good use in optimizing data
structure for which you know that they won't change anymore.
Temporary readonlyness has the nice sideeffect of allowing low-level
lock implementations and makes writing thread safe code easier
to handle, because you can make assertions w/r to the immutability
of an object during a certain period of time explicit in your

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