no-clobber dicts?

Chris Rebert clp2 at rebertia.com
Mon Aug 3 18:00:14 EDT 2009


On Mon, Aug 3, 2009 at 2:47 PM, r<rt8396 at gmail.com> wrote:
> On Aug 3, 4:07 pm, kj <no.em... at please.post> 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
>>
>>   D[K] = V
>>
>> will raise an exception unless V == D[K].  In 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].  All 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.  Before 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
invariant. Otherwise, one will need to look at the UserDict module.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list