sshilovsky sshilovsky - 29 days ago 9
Python Question

How to make dictionary read-only in python

I have a class like:

class A:
def __init__(self):
self.data = {}


and at some moment I want to prohibit
self.data
fields modification.

I've read in PEP-416 rejection notice that there are a lot of ways to do it. So I'd like to find what they are.

I tried this:

a = A()
a.data = types.MappingProxyType(a.data)


That should work but first, its python3.3+ and second, when I do this "prohibition" multiple times I get this:

>>> a.data = types.MappingProxyType(a.data)
>>> a.data = types.MappingProxyType(a.data)
>>> a.data
mappingproxy(mappingproxy({}))


though it would be much better to get just
mappingproxy({})
as I am going to "prohibit" a lot of times. Check of
isinstance(MappingProxyType)
is an option, but I think that other options can exist.

Thanks

Answer

Use collections.Mapping e.g.

import collections

class DictWrapper(collections.Mapping):

    def __init__(self, data):
        self._data = data

    def __getitem__(self, key): 
        return self._data[key]

    def __len__(self):
        return len(self._data)

    def __iter__(self):
        return iter(self._data)

HTH,