Can a Dictionary Be Read-Only? Python's MappingProxyType
This article explains how Python's types.MappingProxyType exposes a live, read-only view of a dictionary, how an object can publish its state through it, and why the view is shallow and no substitute for an immutable mapping.
A dictionary returned by a function or exposed as an attribute can be modified by any code that receives it, so a configuration or an internal registry may change far from the place that owns it. The present article addresses types.MappingProxyType, the standard-library type that wraps a mapping in a read-only view, which Python itself uses for the __dict__ of every class. It shows what the view prevents, explains why it reflects every later change of the wrapped dictionary, and analyses the limits that make it a guard against accidents rather than a frozen or secure dictionary. Letting other code read a mapping freely while only its owner can change it is the secret weapon of MappingProxyType.
Creating a Read-Only View
A proxy is created by passing a mapping to MappingProxyType, and it supports every reading operation of a dictionary: indexing, get, in, len, iteration, keys, values and items. Writing operations are rejected, either with TypeError for item assignment and deletion or with AttributeError for methods such as update and pop, which the type simply does not define. The following example shows both kinds of operations and the class __dict__, which the interpreter exposes in the same way.
from collections.abc import Mapping
from types import MappingProxyType
settings = {"admin": True, "theme": "dark"}
view = MappingProxyType(settings)
print(view["theme"], view.get("lang", "en"), len(view)) # Output: dark en 2
try:
view["theme"] = "light"
except TypeError as error:
print(error) # Output: 'mappingproxy' object does not support item assignment
try:
view.update(theme="light")
except AttributeError as error:
print(error) # Output: 'mappingproxy' object has no attribute 'update'
print(isinstance(view, Mapping), isinstance(view, dict)) # Output: True False
class Config:
debug = False
print(type(Config.__dict__).__name__) # Output: mappingproxy
The proxy satisfies the abstract Mapping interface but is not a dict, which matters for code that checks the exact type. Classes use the same mechanism so that their namespace can be changed only through setattr, which keeps the internal caches of attribute lookup consistent.
Exposing State That Only Its Owner Changes
Many online games give guild members a shared bank whose contents every member can inspect but only officers can withdraw, and a withdrawal appears at once in every member's window. This means that a proxy is not a copy taken at one moment but a live view: the owner keeps the original dictionary, modifies it through its own methods, and every holder of the proxy sees the change immediately. The analogy, however, stops at this point, because the bank enforces its permissions on a server, whereas a proxy only removes the writing methods from one reference and does not protect the dictionary from code that obtains the original. The following example applies the pattern to a registry of plugins.
from types import MappingProxyType
class PluginRegistry:
def __init__(self):
self._plugins = {}
self.plugins = MappingProxyType(self._plugins)
def register(self, name, factory):
if name in self._plugins:
raise ValueError(f"duplicate plugin {name!r}")
self._plugins[name] = factory
registry = PluginRegistry()
current = registry.plugins
registry.register("csv", str)
registry.register("json", repr)
print(list(current)) # Output: ['csv', 'json']
try:
registry.register("csv", int)
except ValueError as error:
print(error) # Output: duplicate plugin 'csv'
snapshot = MappingProxyType(dict(registry.plugins))
registry.register("xml", ascii)
print(len(current), len(snapshot)) # Output: 3 2
The view obtained before any registration lists both plugins, because it reads the same dictionary that register modifies, and every change passes through the validation of the method. When callers need the state of one moment instead, wrapping a copy produces a snapshot that later registrations no longer affect. Live views of several dictionaries at once are the subject of the article devoted to ChainMap.
Pitfalls of MappingProxyType
The proxy removes the writing operations of one mapping and nothing else, so its pitfalls come from expecting the guarantees of an immutable dictionary. Six pitfalls are distinguished, which are the following:
- Shallow protection. Mutable values, such as lists or nested dictionaries, can still be modified through the proxy.
- Live, not frozen. Every change to the original dictionary appears in the view; a stable state requires a proxy over a copy.
- No security boundary. Introspection, for example
gc.get_referents, returns the wrapped dictionary, so the proxy prevents accidents, not deliberate changes. - Not a dict.
isinstance(view, dict)is false, andjson.dumpsrejects a proxy unless it is converted withdict(view). - Copies are mutable.
copy()and the operator|, supported since Python 3.9, return ordinary dictionaries. - No pickling and no hash.
pickleandcopy.copyrefuse the type, and the hashing added in Python 3.12 delegates to the wrapped mapping, so a proxy of a dictionary remains unhashable.
The first, third, fourth and fifth pitfalls are reproduced in the following example.
import gc
import json
from types import MappingProxyType
data = {"roles": ["reader"], "level": 1}
view = MappingProxyType(data)
view["roles"].append("admin")
print(data["roles"]) # Output: ['reader', 'admin']
original = gc.get_referents(view)[0]
original["level"] = 99
print(view["level"]) # Output: 99
try:
json.dumps(view)
except TypeError as error:
print(error) # Output: Object of type mappingproxy is not JSON serializable
print(json.dumps(dict(view))) # Output: {"roles": ["reader", "admin"], "level": 99}
merged = view | {"level": 2}
print(type(merged).__name__, view["level"]) # Output: dict 99
The list inside the proxy accepted a new element, the garbage collector handed back the dictionary itself, and the merge produced an independent dictionary while the view remained unchanged. Reading through a proxy cost about 24 nanoseconds against 22 for the dictionary on CPython 3.12, so the protection is practically free.
Choosing a Read-Only Mapping
Consequently, MappingProxyType suits mappings whose owner must keep changing them while other code only reads them, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| A mapping that its owner updates and others only read | MappingProxyType over the owner's dictionary |
| A fixed snapshot for callers | MappingProxyType(dict(original)) |
| A hashable, immutable mapping in Python 3.14 | A frozenset or a tuple of items, or a frozen data class |
| A built-in immutable dictionary | frozendict, accepted in PEP 814 for Python 3.15 |
| Immutable values inside the mapping | Tuples, frozensets or frozen data classes as values |
| Serializing the contents | dict(view) before json.dumps |
| Protection from deliberately hostile code | Process or service boundaries, not a proxy |
Frozen data classes are examined in the article devoted to data classes, and the hashing rules that any immutable mapping must respect in the article devoted to the dictionary.
Conclusion
It is concluded that MappingProxyType exposes a live, read-only view of a mapping, that it rejects assignment, deletion and every writing method, and that it lets an object publish its state while keeping all changes inside its own methods. This magic is shallow and local: nested values remain mutable, the original dictionary stays reachable, and copies, merges and serialization produce ordinary dictionaries. Ordering tasks so that each one runs only after the tasks it depends on is the purpose of the module graphlib, which is developed in a future article of this series.