]> granicus.if.org Git - python/commitdiff
Issue #5647: MutableSet.__iand__() no longer mutates self during iteration.
authorRaymond Hettinger <python@rcn.com>
Wed, 1 Apr 2009 19:05:50 +0000 (19:05 +0000)
committerRaymond Hettinger <python@rcn.com>
Wed, 1 Apr 2009 19:05:50 +0000 (19:05 +0000)
Lib/_abcoll.py
Lib/test/test_collections.py
Misc/NEWS

index 45747a6c49ba127ae60b7a9f92f652d48589c17f..7b01178a05443810698c15a00167eeca1abc3f08 100644 (file)
@@ -320,10 +320,9 @@ class MutableSet(Set):
             self.add(value)
         return self
 
-    def __iand__(self, c: Container):
-        for value in self:
-            if value not in c:
-                self.discard(value)
+    def __iand__(self, it: Iterable):
+        for value in (self - it):
+            self.discard(value)
         return self
 
     def __ixor__(self, it: Iterable):
index 3d00973ab189ca54d3a7462a2e00a24475455524..e8d72ee57ad177b409f8cb9257269f5cad163e3a 100644 (file)
@@ -327,6 +327,25 @@ class TestOneTrickPonyABCs(ABCTestCase):
             B.register(C)
             self.failUnless(issubclass(C, B))
 
+class WithSet(MutableSet):
+
+    def __init__(self, it=()):
+        self.data = set(it)
+
+    def __len__(self):
+        return len(self.data)
+
+    def __iter__(self):
+        return iter(self.data)
+
+    def __contains__(self, item):
+        return item in self.data
+
+    def add(self, item):
+        self.data.add(item)
+
+    def discard(self, item):
+        self.data.discard(item)
 
 class TestCollectionABCs(ABCTestCase):
 
@@ -363,6 +382,12 @@ class TestCollectionABCs(ABCTestCase):
         self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__',
             'add', 'discard')
 
+    def test_issue_5647(self):
+        # MutableSet.__iand__ mutated the set during iteration
+        s = WithSet('abcd')
+        s &= WithSet('cdef')            # This used to fail
+        self.assertEqual(set(s), set('cd'))
+
     def test_issue_4920(self):
         # MutableSet.pop() method did not work
         class MySet(collections.MutableSet):
index 2ecd85b0dead8351ea1b6571a530ecc51071d255..f003c0a0502fff905c3c73def0ef9216c26a8355 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -55,6 +55,8 @@ Core and Builtins
 Library
 -------
 
+- Issue #5647: MutableSet.__iand__() no longer mutates self during iteration.
+
 - Issue #5624: Fix the _winreg module name still used in several modules.
 
 - Issue #5628: Fix io.TextIOWrapper.read() with a unreadable buffer.