Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 919
sshilovsky Avatar asked Sep 26 '13 08:09

sshilovsky


People also ask

How do you only get values from a dictionary?

If you only need the dictionary values -0.3246 , -0.9185 , and -3985 use: your_dict. values() . If you want both keys and values use: your_dict. items() which returns a list of tuples [(key1, value1), (key2, value2), ...] .

Which are read-only list which Cannot be modified in Python?

Tuples are, for most intents and purposes, 'immutable lists' - so by nature they will act as read-only objects that can't be directly set or modified.


1 Answers

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) 
like image 140
mouad Avatar answered Sep 21 '22 16:09

mouad