Hi Pythonistas!
Today, we will learn about MappingProxyType, a powerful tool that allows us to create a read-only yet dynamic view of a dictionary. MappingProxyType provides us with a read-only copy of another dictionary, and interestingly, its values will reflect any changes made to the original dictionary. Let us learn this by an example
Create mappingproxytype
from types import MappingProxyType
original_dict = {'a': 1, 'b': 2, 'c': 3}
read_only_dict = MappingProxyType(original_dict)
Print object
print(read_only_dict)
Output
{'a': 1, 'b': 2, 'c': 3}
Accessing object
print(read_only_dict['a'])
Output
1
Print all keys
print(read_only_dict.keys())
Output
dict_keys(['a', 'b', 'c'])
Print all values
print(read_only_dict.values())
Output
dict_values([1, 2, 3])
Everything on dict works for this objects. But write operation fails
read_only_dict['a']=10
Output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment
Now we can update original dict
original_dict["d"]=4
print(read_only_dict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
We can see that read only dict updated on changing original dict.
When it is useful
We can use this for configuration management, serialization, plugin development etc.
Hope you have learned something new from this post. Please share your valuable suggestions with afsal@parseltongue.co.in