no-clobber dicts?

Chris Rebert clp2 at
Tue Aug 4 22:03:08 CEST 2009

On Tue, Aug 4, 2009 at 12:30 PM, kj< at> wrote:
> In <mailman.4183.1249336823.8015.python-list at> Chris Rebert <clp2 at> writes:
>>On Mon, Aug 3, 2009 at 2:47 PM, r<rt8396 at> wrote:
>>> On Aug 3, 4:07=C2=A0pm, kj <no.em... at> wrote:
>>>> I use the term "no-clobber dict" to refer to a dictionary D with
>>>> the especial property that if K is in D, then
>>>> =C2=A0 D[K] =3D V
>>>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K]
>>>> can be set if K doesn't exist already among D's keys, or if the
>>>> assigned value is equal to the current value of D[K]. =C2=A0All other
>>>> assignments to D[K] trigger an exception.
>>>> The idea here is to detect inconsistencies in the data.
>>>> This is a data structure I often need. =C2=A0Before I re-invent the
>>>> wheel, I thought I'd ask: is it already available?
>>>> TIA!
>>>> kynn
>>> Not sure if something like this already exists, but it would be
>>> trivial to implement by overriding dict.__setitem__()
>>That is, if you don't care about .update() not preserving the
> The implication here is that .update() does not in turn use
> .__setitem__(), which I find a bit surprising.

The builtin types are allowed to take such shortcuts for performance reasons.


More information about the Python-list mailing list