Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7aebb64

Browse files
committed
Document how to use Set and MutableSet as a mixin.
1 parent 74b6495 commit 7aebb64

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

Doc/library/collections.rst

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ ABC Inherits Abstract Methods Mixin M
5858
``insert``, ``remove``, and ``__iadd__``
5959
and ``__len__``
6060

61-
:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
61+
:class:`Set` \(1) \(2) :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
6262
:class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
6363
:class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
6464

@@ -100,6 +100,23 @@ The ABC supplies the remaining methods such as :meth:`__and__` and
100100
s2 = ListBasedSet('defghi')
101101
overlap = s1 & s2 # The __and__() method is supported automatically
102102

103+
Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
104+
105+
(1)
106+
Since some set operations create new sets, the default mixin methods need
107+
a way to create new instances from an iterable. The class constructor is
108+
assumed to have a signature in the form ``ClassName(iterable)``.
109+
That assumption is factored-out to a singleinternal classmethod called
110+
:meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
111+
If the :class:`Set` mixin is being used in a class with a different
112+
constructor signature, you will need to override :meth:`from_iterable`
113+
with a classmethod that can construct new instances from
114+
an iterable argument.
115+
116+
(2)
117+
To override the comparisons (presumably for speed, as the
118+
semantics are fixed), redefine :meth:`__le__` and
119+
then the other operations will automatically follow suit.
103120

104121
(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
105122

Lib/_abcoll.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,9 @@ def _from_iterable(cls, it):
207207
'''Construct an instance of the class from any iterable input.
208208
209209
Must override this method if the class constructor signature
210-
will not accept a frozenset for an input.
210+
does not accept an iterable for an input.
211211
'''
212-
return cls(frozenset(it))
212+
return cls(it)
213213

214214
def __and__(self, other):
215215
if not isinstance(other, Iterable):

0 commit comments

Comments
 (0)