Skip to content

Commit eb03dbd

Browse files
gh-162644: Raise TypeError when pickling a weakref.ref subclass with protocol 0 or 1 (GH-162728)
Previously it caused infinite recursion. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 235d138 commit eb03dbd

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

‎Lib/copyreg.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ def _reduce_ex(self, proto):
119119
if base is object:
120120
state = None
121121
else:
122-
if base is cls:
122+
# For weakref.ref, base(self) would be a new reference to self.
123+
if base is cls or base is _ref:
123124
raise TypeError(f"cannot pickle {cls.__name__!r} object")
124125
state = base(self)
125126
args = (cls, base, state)

‎Lib/test/pickletester.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1816,6 +1816,9 @@ class WeakrefTarget:
18161816
# error path must not assume hashable referents.
18171817
__hash__ = None
18181818

1819+
class WeakrefSubclass(weakref.ref):
1820+
pass
1821+
18191822

18201823
class AbstractPicklingErrorTests:
18211824
# Subclass must define self.dumps, self.pickler.
@@ -1877,6 +1880,14 @@ def test_proxy_without_strong_ref(self):
18771880
[copyreg.Proxy(obj), copyreg.Proxy(obj)],
18781881
proto)
18791882

1883+
def test_weakref_subclass_errors(self):
1884+
# gh-162644: no infinite recursion with protocols 0 and 1.
1885+
obj = WeakrefTarget()
1886+
wr = WeakrefSubclass(obj)
1887+
for proto in protocols:
1888+
with self.subTest(proto=proto):
1889+
self.assertRaises(TypeError, self.dumps, [obj, wr], proto)
1890+
18801891
def test_bad_reduce_result(self):
18811892
obj = REX([print, ()])
18821893
for proto in protocols:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Pickling a :class:`weakref.ref` subclass with protocol 0 or 1
2+
now raises :exc:`TypeError` instead of :exc:`RecursionError`.

0 commit comments

Comments
 (0)