Articles icon indicating copy to clipboard operation
Articles copied to clipboard

types.MappingProxyType isn't read-only in nested sections of dict

Open vitaly-krugl opened this issue 5 years ago • 0 comments

The "new interesting data types" file claims that types.MappingProxyType can be used to pass a dict to functions without the risk of it being modified. However, this is only true about the top level properties of the dict. Any nested properties/structures can still be modified as the following example demonstrates:

$ ipython
Python 3.7.5 (default, Nov  1 2019, 02:16:32) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.9.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import types                                                            

In [2]: d = { 
   ...: 'a': 1, 
   ...: 'b': {'c': 2} 
   ...: }                                                                       

In [3]: p = types.MappingProxyType(d)                                           

# NOTE that top-level properties are protected
In [4]: p['a'] = 9                                                              
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-5c54e242859d> in <module>
----> 1 p['a'] = 9

TypeError: 'mappingproxy' object does not support item assignment

# *** But nested structures are not protected, therefore the dict is not read-only!
In [5]: p['b']['c'] = 20                                                        

In [6]: p                                                                       
Out[6]: mappingproxy({'a': 1, 'b': {'c': 20}})

In [7]:             

vitaly-krugl avatar Jan 29 '20 21:01 vitaly-krugl