Python Glossary Русский

Python 3.3+collectionsterm

collections.abc.MutableSet

collections.abc — protocols

The mutable set protocol (set): add/discard.

Syntax

isinstance(obj, collections.abc.MutableSet)

Implementing one means writing just __contains__, __iter__, __len__, add and discard; clear, pop, remove and the in-place |=, &=, -=, ^= operators are supplied by the mixins. Note that add's counterpart discard is silent about missing elements while remove raises KeyError — same idea, different contracts. frozenset and view objects such as dict.keys() register as Set but never as MutableSet, since nothing can be inserted into them.

Examples

import collections.abc as abc
print(isinstance(set(), abc.MutableSet))         # → True
print(isinstance(frozenset(), abc.MutableSet))   # → False
print(isinstance(frozenset(), abc.Set))   # → True
print(isinstance({}.keys(), abc.Set))   # → True
s = {1, 2}; s.discard(3); print(s)   # → {1, 2}
print(sorted(abc.MutableSet.__abstractmethods__))   # → ['__contains__', '__iter__', '__len__', 'add', 'discard']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy