no-clobber dicts?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Aug 3 23:23:20 EDT 2009


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



I also have a series of unit tests for it if you're interested in them.




-- 
Steven



More information about the Python-list mailing list