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
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), ...] .
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.
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) 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With