sshilovsky sshilovsky - 9 months ago 52
Python Question

How to make dictionary read-only in python

I have a class like:

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

and at some moment I want to prohibit
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() = types.MappingProxyType(

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

>>> = types.MappingProxyType(
>>> = types.MappingProxyType(

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


Answer Source

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)