Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
vitaly-krugl opened this issue Jan 29, 2020 · 0 comments
Open

Comments

@vitaly-krugl
Copy link

vitaly-krugl commented Jan 29, 2020

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]:             
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant