diff --git a/Lib/_weakrefset.py b/Lib/_weakrefset.py index d1c7fcaeec9821..d6e31a18cf254d 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 c1e4f9c8366e58..b26c023470ec3f 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 00000000000000..cd799e3ceb9db8 --- /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.