[Python-ideas] Immutable dictionaries

Victor Stinner victor.stinner at gmail.com
Wed Nov 29 13:03:41 EST 2017


2017-11-29 18:30 GMT+01:00 Asen Bozhilov <asen.bozhilov at gmail.com>:
> I'd like to propose also literaling syntax for immutable dictionaries.
>
> immutable_dict = (
>     'key1' : 'value1',
>     'key2' : 'value2'
> )

Since Python 3.3, you can write:

vstinner at apu$ python3
Python 3.6.3 (default, Oct  9 2017, 12:07:10)
>>> import types
>>> immutable_dict = types.MappingProxyType({"key": "value"})

>>> immutable_dict.pop('key')
AttributeError: 'mappingproxy' object has no attribute 'pop'

>>> immutable_dict['key'] = 'value2'
TypeError: 'mappingproxy' object does not support item assignment

>>> immutable_dict['key2'] = 'value3'
TypeError: 'mappingproxy' object does not support item assignment

Maybe not the ideal syntax, but it already works without having to
modify the Python syntax, and it works on Python 3.3 and newer ;-)

Victor


More information about the Python-ideas mailing list