Using types.MappingProxyType to create immutable mappings

types.MappingProxyType is a wrapper object that allows you to create an immutable mapping based on an existing dictionary. It provides read-only access to the dictionary's data while preventing modifications, which is useful for protecting data from accidental changes.

In this example, MappingProxyType is used to create a protected mapping.

MappingProxyType helps safeguard data that should not be altered during the execution of a program.

from types import MappingProxyType

original_dict = {'key1': 'value1', 'key2': 'value2'}
proxy_dict = MappingProxyType(original_dict)

print(proxy_dict['key1']) # Output: value1

# proxy_dict['key1'] = 'new_value' # Raises an error because the dictionary is immutable

Comments (0)

Leave a comment