Python Glossary Русский

Python 3.3+collectionsterm

collections.abc.MutableMapping

collections.abc — protocols

The mutable mapping protocol (dict): adds __setitem__/__delitem__/update.

Syntax

isinstance(obj, collections.abc.MutableMapping)

Use it as a type check when you care that something is key-addressable and writable rather than literally a dict — os.environ and hand-written mapping classes pass, dict subclass checks would miss them. Subclassing is the real payoff: implement __getitem__, __setitem__, __delitem__, __iter__ and __len__, and the mixins hand you get, pop, setdefault, update, items and keys for free. Import it from collections.abc — the old collections.MutableMapping alias was dropped in Python 3.10.

Examples

import collections.abc as abc
from types import MappingProxyType
print(isinstance({}, abc.MutableMapping))   # → True
d = {'a': 1}; d.update(b=2); print(d)   # → {'a': 1, 'b': 2}
print(isinstance(MappingProxyType({'a': 1}), abc.Mapping))   # → True
print(isinstance(MappingProxyType({'a': 1}), abc.MutableMapping))   # → False
print(sorted(abc.MutableMapping.__abstractmethods__))   # → ['__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy