[Python-Dev] Re: Pre-PEP: Mutable keys in dictionaries

Just van Rossum just@letterror.com
Thu, 6 Feb 2003 19:25:56 +0100


Eric wrote:

> Just van Rossum wrote:
> 
> [snip]
> > 
> > The __temporary_immutable__ part of the protocol is needed to avoid
> > unneccesary copying in those cases where the key isn't actually
> > inserted into the dict, but is only used for membership testing. It
> > would return a wrapper around the mutable object, defining __eq__
> > and __hash__. (This idea is stolen from the sets.py module.) If an
> > implementer doesn't care about this efficiency,
> > __temporary_immutable__ can be an alias to __immutable_copy__.
> 
> Can __temporary_immutable__ work on a multi-threaded system?  What is
> to prevent the (known to be mutable) key from changing underneath you
> during the lookup?  Perhaps I am misunderstanding, but it seems to me
> that you must either copy the mutable key or be able to block all
> writers to the key during the lookup.

Provided the underlying mutable object is a Python object, there is no
chance that the object can change during the operation, due to the
wonders of the Global Interpreter Lock. When integrated with
dictobject.c it is guaranteed that the operation is atomic. I'll make
sure this gets added to the PEP.

> Other than that, I very much like the idea of using mutable keys :)

In certain circumstances, yes, however I would by no means propose that
Python dicts and lists should support this protocol themselves, ie. it
should remain impossible to use dicts and lists as keys. A) because it
would cause confusion, B) because it would be hard to implement with
respect to nested objects (eg. what about a tuple containing a dict?).

Just