The MappingProxyType class takes a dictionary entry that returns a read-only mapping view 1. This view object is affected by the original dictionary object, which means that if the contents of the original dictionary object change, the view object will also change.

dict={1: 'A'}
not_modify_dict=MappingProxyType(dict)
logging.info('not_modify_dict -> %s', not_modify_dict)
logging.info('not_modify_dict[1] -> %s', not_modify_dict[1])
# not_modify_dict[2]='B'
dict[2]= 'B'
logging.info('not_modify_dict -> %s', not_modify_dict)
logging.info('not_modify_dict[2] -> %s', not_modify_dict[2])
Copy the code

Running results:

INFO - not_modify_dict -> {1: 'A'}
INFO - not_modify_dict[1] -> A
INFO - not_modify_dict -> {1: 'A', 2: 'B'}
INFO - not_modify_dict[2] -> B
Copy the code

If not_modify_dict[2]=’B’ is assigned here, TypeError will be raised: ‘MappingProxy’ object does not support item Assignment.

So the MappingProxyType class object is suitable for scenarios that cannot be modified once initialized.


[1] Luciano Ramalho (author), An Dao, Wu Ke (translator). Smooth Python. Posts and Telecommunications Press, 2017:154-155.