Skip to content

Commit d805bc8

Browse files
gh-162802: Forbid copying of weakref.WeakSet
copy.copy() and copy.deepcopy() of WeakSet created broken copies which shared internal state with the original. Now they raise TypeError. Use the copy() method instead.
1 parent 2eb0c9a commit d805bc8

3 files changed

Lines changed: 16 additions & 18 deletions

File tree

‎Lib/_weakrefset.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ def __contains__(self, item):
4242
def __reduce__(self):
4343
return self.__class__, (list(self),), self.__getstate__()
4444

45+
def __copy__(self):
46+
raise TypeError(f"cannot copy {type(self).__name__!r} object")
47+
48+
def __deepcopy__(self, memo):
49+
raise TypeError(f"cannot copy {type(self).__name__!r} object")
50+
4551
def add(self, item):
4652
self.data.add(ref(item, self._remove))
4753

‎Lib/test/test_weakset.py‎

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -457,26 +457,14 @@ def test_abc(self):
457457
def test_copying(self):
458458
for cls in WeakSet, WeakSetWithSlots:
459459
s = cls(self.items)
460-
s.x = ['x']
461-
s.z = ['z']
462-
463-
dup = copy.copy(s)
464-
self.assertIsInstance(dup, cls)
465-
self.assertEqual(dup, s)
466-
self.assertIsNot(dup, s)
467-
self.assertIs(dup.x, s.x)
468-
self.assertIs(dup.z, s.z)
469-
self.assertNotHasAttr(dup, 'y')
470-
471-
dup = copy.deepcopy(s)
460+
with self.assertRaises(TypeError):
461+
copy.copy(s)
462+
with self.assertRaises(TypeError):
463+
copy.deepcopy(s)
464+
dup = s.copy()
472465
self.assertIsInstance(dup, cls)
473466
self.assertEqual(dup, s)
474-
self.assertIsNot(dup, s)
475-
self.assertEqual(dup.x, s.x)
476-
self.assertIsNot(dup.x, s.x)
477-
self.assertEqual(dup.z, s.z)
478-
self.assertIsNot(dup.z, s.z)
479-
self.assertNotHasAttr(dup, 'y')
467+
self.assertIsNot(dup.data, s.data)
480468

481469

482470
if __name__ == "__main__":
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:func:`copy.copy` and :func:`copy.deepcopy` of :class:`weakref.WeakSet`
2+
now raise :exc:`TypeError` instead of creating a broken copy
3+
which shares internal state with the original.
4+
Use the :meth:`!copy` method instead.

0 commit comments

Comments
 (0)