How to Use MappingProxyType to Create Immutable Dict Views in Python
Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.
Python code
22 linesfrom types import MappingProxyType
config = {"debug": True, "port": 8080}
# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)
print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")
# Original dict can still be modified
config["port"] = 9090
print(f"View reflects changes: {read_only_config['port']}")
# Attempting to modify the immutable view raises TypeError
try:
read_only_config["debug"] = False
except TypeError as e:
print(f"Modification blocked: {e}")
# Show all items through the view
print(f"Items: {dict(read_only_config)}")
Output
Read-only value: True
Dict is mapping: True
View reflects changes: 9090
Modification blocked: 'mappingproxy' object does not support item assignment
Items: {'debug': True, 'port': 9090}
How it works
MappingProxyType(config) wraps the original dict in a read-only mapping. The proxy is a live view — changes to the original dict appear through the proxy. Accessing items works exactly like a normal dict, but assigning proxy['key'] = value raises TypeError. Use this when you need to pass a dict to other code without letting it mutate your data. The proxy is not a copy; modifying the original dict still updates what the proxy sees.
Common mistakes
- Confusing MappingProxyType with deepcopy — the proxy is a view, not a copy
- Expecting the proxy to be an instance of dict — use isinstance(obj, Mapping) instead
- Trying to update the proxy after creation, which always raises TypeError
Variations
- Use `Mapping` from collections.abc for type hints instead of dict
- Wrap a `ChainMap` or `defaultdict` in MappingProxyType for a read-only facade
Real-world use cases
- Exposing application configuration to plugins without letting them overwrite settings
- Returning a read-only snapshot of a cached dataset to API consumers
- Passing a protected dictionary to a worker thread so it cannot corrupt shared state
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.