Search code examples
pythonclasssubclassimmutability

How to create an immutable dictionary in python?


I want to subclass dict in python such that all the dictionaries of the sub-class are immutable.

I don't understand how does __hash__ affects the immutability, since in my understanding it just signifies the equality or non-equality of objects !

So, can __hash__ be used to implement immutability ? How ?

Update:

Objective is that common response from an API is available as a dict, which has to be shared as a global variable. So, that needs to be intact no matter what ?


Solution

  • I found a Official reference : suggestion contained in a rejected PEP.

    class imdict(dict):
        def __hash__(self):
            return id(self)
    
        def _immutable(self, *args, **kws):
            raise TypeError('object is immutable')
    
        __setitem__ = _immutable
        __delitem__ = _immutable
        clear       = _immutable
        update      = _immutable
        setdefault  = _immutable
        pop         = _immutable
        popitem     = _immutable
    

    Attribution : http://www.python.org/dev/peps/pep-0351/