Skip to content

Commit a24ccf4

Browse files
gh-74876: Do not call reducer_override() for copyreg.Proxy in pickle.py
The Python implementation of the pickler now checks for copyreg.Proxy before calling reducer_override(), like the C implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b38f173 commit a24ccf4

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎Doc/library/pickle.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,7 @@ If both the :attr:`~Pickler.dispatch_table` and
924924
exact instances of :class:`int`, :class:`float`, :class:`bytes`,
925925
:class:`str`, :class:`dict`, :class:`set`, :class:`frozenset`, :class:`list`
926926
and :class:`tuple`.
927+
It is never called for :class:`copyreg.Proxy` objects.
927928

928929
Here is a simple example where we allow pickling and reconstructing
929930
a given class::

‎Lib/pickle.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,10 @@ def save(self, obj, save_persistent_id=True, weak=False):
590590
self.write(self.get(x[0]))
591591
return
592592

593+
if type(obj) is Proxy:
594+
self.save_proxy(obj)
595+
return
596+
593597
rv = NotImplemented
594598
reduce = getattr(self, "reducer_override", _NoValue)
595599
if reduce is not _NoValue:
@@ -1298,8 +1302,6 @@ def save_proxy(self, obj):
12981302
if not anchored and i in self.memo:
12991303
self._weak_only.add(i)
13001304

1301-
dispatch[Proxy] = save_proxy
1302-
13031305

13041306
# Unpickling machinery
13051307

‎Lib/test/pickletester.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5603,6 +5603,24 @@ def f():
56035603

56045604
self.assertIsNone(wr())
56055605

5606+
def test_reducer_override_not_called_for_proxy(self):
5607+
seen = []
5608+
class MyPickler(self.pickler_class):
5609+
def reducer_override(self, obj):
5610+
seen.append(type(obj))
5611+
return NotImplemented
5612+
5613+
obj = Object()
5614+
for proto in protocols:
5615+
with self.subTest(proto=proto):
5616+
seen.clear()
5617+
bio = io.BytesIO()
5618+
MyPickler(bio, proto).dump([obj, copyreg.Proxy(obj)])
5619+
self.assertIn(Object, seen)
5620+
self.assertNotIn(copyreg.Proxy, seen)
5621+
obj2, obj3 = pickle.loads(bio.getvalue())
5622+
self.assertIs(obj3, obj2)
5623+
56065624

56075625
class AbstractDispatchTableTests:
56085626

0 commit comments

Comments
 (0)