[Python-Dev] Re: Sets: elt in dict, lst.include

Finn Bock bckfnn@worldonline.dk
Tue, 30 Jan 2001 17:34:10 GMT


>Maybe we could add a flag to the dict that issues an error when a new
>key is inserted during such a for loop?  

FWIW, some of the java2 collections decided to throw a Concurrent-
ModificationException in the iterator if the collection was modified
during the iteration. Generally none of java2 collections can be
modified while iterating over it (the exception is calling .remove() on
the iterator object and not all collections support that).

>(I don't think the key order can be affected when a key is *deleted*.)

Probably also true for the Hashtables which is backing our PyDictionary,
but I'll rather not depend too much on it being true.


>That latter is true but specific to this implementation.  "Can't mutate the
>dict period" is easier to keep straight, and probably harmless in practice
>(if not, it could be relaxed later).  


>Recall that a similar trick is played
>during list.sort(), replacing the list's type pointer for the duration (to
>point to an internal "immutable list" type, same as the list type except the
>"dangerous" slots point to a function that raises an "immutable list"
>TypeError).  Then no runtime expense is incurred for regular lists to keep
>checking flags.  I thought of this as an elegant use for switching types at
>runtime; you may still be appalled by it, though!

Changing the type of a type? Yuck! 

I might very likely be reading the CPython sources wrongly, but it seems
this trick will cause an BadInternalCall if some other C extension are
trying to modify a list while it is freezed by the type switching trick.
I imagine this would happen if the extension called:

  PyList_SetItem(myList, 0, aValue);

I guess Jython could support this from the python side, but its hard to
ensure from the java side without adding an additional PyList_Check(..)
to all list methods. It just doesn't feel like the right thing to go
since it would cause slower access to all mutable objects.