no-clobber dicts?

kj no.email at please.post
Tue Aug 4 15:29:00 EDT 2009


In <pan.2009.08.04.03.23.19 at REMOVE.THIS.cybersource.com.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:

>On Mon, 03 Aug 2009 21:07:32 +0000, kj 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.


>Coincidentally, I just built something very close to what you ask. Here 
>it is:

>class ConstantNamespace(dict):
>    """Dictionary with write-once keys."""
>    def __delitem__(self, key):
>        raise TypeError("can't unbind constants")
>    def __setitem__(self, key, value):
>        if key in self:
>            raise TypeError("can't rebind constants")
>        super(ConstantNamespace, self).__setitem__(key, value)
>    def clear(self):
>        raise TypeError('cannot unbind constants')
>    def pop(self, key, *args):
>        raise TypeError("cannot pop constants")
>    def popitem(self):
>        raise TypeError("cannot pop constants")
>    def update(self, other):
>        for key in other:
>            if key in self:
>                raise TypeError('cannot update constants')
>        # If we get here, then we're not modifying anything, 
>        # so okay to proceed.
>        super(ConstantNamespace, self).update(other)
>    def copy(self):
>        c = self.__class__(**self)
>        return c


Thanks.  As you note this not quite what I'm looking for, but it's
a good template for it.

kynn



More information about the Python-list mailing list