@@ -1817,6 +1817,10 @@ class WeakrefTarget:
18171817 __hash__ = None
18181818
18191819
1820+ class WeakrefSubclass (weakref .ref ):
1821+ pass
1822+
1823+
18201824class AbstractPicklingErrorTests :
18211825 # Subclass must define self.dumps, self.pickler.
18221826
@@ -1829,6 +1833,31 @@ def test_unpicklable_weakref_referent(self):
18291833 with self .subTest (proto = proto ):
18301834 self .assertRaises (pickle .PicklingError , self .dumps , wr , proto )
18311835
1836+ def test_weakref_subclass (self ):
1837+ # With protocols 0 and 1 the reduce arguments of the instance contain
1838+ # a weak reference to the instance itself.
1839+ obj = WeakrefTarget ()
1840+ wr = WeakrefSubclass (obj )
1841+ msg = "cannot pickle 'WeakrefSubclass' object"
1842+ for proto in protocols :
1843+ with self .subTest (proto = proto ):
1844+ with self .assertRaisesRegex (TypeError , msg ):
1845+ self .dumps ([obj , wr ], proto )
1846+ with self .assertRaisesRegex (TypeError , msg ):
1847+ self .dumps ([obj , weakref .ref (wr ), wr ], proto )
1848+
1849+ def test_weakref_to_self_in_reduce_args (self ):
1850+ # The object cannot be created without a weak reference to itself.
1851+ obj = K (None )
1852+ obj .value = weakref .ref (obj )
1853+ msg = "cannot pickle 'K' object"
1854+ for proto in protocols :
1855+ with self .subTest (proto = proto ):
1856+ with self .assertRaisesRegex (TypeError , msg ):
1857+ self .dumps (obj , proto )
1858+ with self .assertRaisesRegex (TypeError , msg ):
1859+ self .dumps ([obj .value , obj ], proto )
1860+
18321861 def test_weakref_without_strong_ref (self ):
18331862 # The error names the distinct referent types: bounded however many
18341863 # referents there are, and not requiring them to be hashable.
@@ -3651,6 +3680,27 @@ def test_weakref(self):
36513680 wr2 , obj2 = self .loads (self .dumps ([wr , obj ], proto ))
36523681 self .assertIs (wr2 (), obj2 )
36533682
3683+ def test_weakref_in_reduce_args (self ):
3684+ if self .py_version < (3 , 16 ):
3685+ self .skipTest ('not supported in Python < 3.16' )
3686+ # The object is created from a list containing a weak reference to
3687+ # the object.
3688+ value = []
3689+ obj = K (value )
3690+ wr = weakref .ref (obj )
3691+ value .append (wr )
3692+ for proto in protocols :
3693+ with self .subTest (proto = proto ):
3694+ obj2 , wr2 = self .loads (self .dumps ([obj , wr ], proto ))
3695+ self .assertIsInstance (obj2 , K )
3696+ self .assertIs (wr2 (), obj2 )
3697+ self .assertIs (obj2 .value [0 ], wr2 )
3698+ # Identity holds regardless of pickling order.
3699+ wr2 , obj2 = self .loads (self .dumps ([wr , obj ], proto ))
3700+ self .assertIsInstance (obj2 , K )
3701+ self .assertIs (wr2 (), obj2 )
3702+ self .assertIs (obj2 .value [0 ], wr2 )
3703+
36543704 def test_weakref_callback (self ):
36553705 if self .py_version < (3 , 16 ):
36563706 self .skipTest ('not supported in Python < 3.16' )
0 commit comments