From d805bc84a6a02e188019ac13e3ccfcedab7fe077 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sat, 28 Nov 2026 12:58:38 +0200 Subject: [PATCH] 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. --- Lib/_weakrefset.py | 6 +++++ Lib/test/test_weakset.py | 24 +++++-------------- ...-11-28-12-00-00.gh-issue-162802.WSnoCp.rst | 4 ++++ 3 files changed, 16 insertions(+), 18 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162802.WSnoCp.rst diff --git a/Lib/_weakrefset.py b/Lib/_weakrefset.py index d1c7fcaeec9821c..d6e31a18cf254df 100644 --- a/Lib/_weakrefset.py +++ b/Lib/_weakrefset.py @@ -42,6 +42,12 @@ def __contains__(self, item): def __reduce__(self): return self.__class__, (list(self),), self.__getstate__() + def __copy__(self): + raise TypeError(f"cannot copy {type(self).__name__!r} object") + + def __deepcopy__(self, memo): + raise TypeError(f"cannot copy {type(self).__name__!r} object") + def add(self, item): self.data.add(ref(item, self._remove)) diff --git a/Lib/test/test_weakset.py b/Lib/test/test_weakset.py index c1e4f9c8366e58a..b26c023470ec3fa 100644 --- a/Lib/test/test_weakset.py +++ b/Lib/test/test_weakset.py @@ -457,26 +457,14 @@ def test_abc(self): def test_copying(self): for cls in WeakSet, WeakSetWithSlots: s = cls(self.items) - s.x = ['x'] - s.z = ['z'] - - dup = copy.copy(s) - self.assertIsInstance(dup, cls) - self.assertEqual(dup, s) - self.assertIsNot(dup, s) - self.assertIs(dup.x, s.x) - self.assertIs(dup.z, s.z) - self.assertNotHasAttr(dup, 'y') - - dup = copy.deepcopy(s) + with self.assertRaises(TypeError): + copy.copy(s) + with self.assertRaises(TypeError): + copy.deepcopy(s) + dup = s.copy() self.assertIsInstance(dup, cls) self.assertEqual(dup, s) - self.assertIsNot(dup, s) - self.assertEqual(dup.x, s.x) - self.assertIsNot(dup.x, s.x) - self.assertEqual(dup.z, s.z) - self.assertIsNot(dup.z, s.z) - self.assertNotHasAttr(dup, 'y') + self.assertIsNot(dup.data, s.data) if __name__ == "__main__": diff --git a/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162802.WSnoCp.rst b/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162802.WSnoCp.rst new file mode 100644 index 000000000000000..cd799e3ceb9db87 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162802.WSnoCp.rst @@ -0,0 +1,4 @@ +:func:`copy.copy` and :func:`copy.deepcopy` of :class:`weakref.WeakSet` +now raise :exc:`TypeError` instead of creating a broken copy +which shares internal state with the original. +Use the :meth:`!copy` method instead.