Python Glossary Русский

Python 3.0+collectionsterm

collections.UserDict

type wrappers

A dict wrapper keeping its contents in .data; a base for your own dict classes, since every method goes through .data unlike subclassing dict directly.

Syntax

class MyDict(collections.UserDict): ...

The wrapper exists for subclassing: derive from dict directly and your overridden __setitem__ gets quietly bypassed by update(), setdefault() and the constructor, which are C-level and write straight into the storage; UserDict funnels every write through your method instead. The cost is speed plus the fact that isinstance(obj, dict) is False, so code that type-checks will reject the object — pass .data there.

Examples

from collections import UserDict
d = UserDict({'a': 1})
d['b'] = 2
print(d['a'], d['b'], isinstance(d.data, dict))   # → 1 2 True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy