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.

Easy Python 3.3+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

22 lines
Python 3.3+
from 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

stdout
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

  1. Use `Mapping` from collections.abc for type hints instead of dict
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.