Skip to content

Commit 937828f

Browse files
gh-74876: Add copyreg.Proxy (GH-160219)
A copyreg.Proxy is pickled as the wrapped object, which must be strongly referenced elsewhere in the same pickle. It replaces the native support of weak references in pickle: weakref.ref, WeakMethod, WeakSet, WeakValueDictionary and WeakKeyDictionary are now reduced using Proxy. The copy module supports Proxy too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5dbe2ac commit 937828f

16 files changed

Lines changed: 308 additions & 182 deletions

‎Doc/library/copyreg.rst‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,30 @@ Such constructors may be factory functions or class instances.
3939
object or subclass of :class:`pickle.Pickler` can also be used for
4040
declaring reduction functions.
4141

42+
43+
.. class:: Proxy(obj)
44+
45+
A wrapper for an object which is pickled weakly.
46+
Reduction functions can use it to pickle objects
47+
to which the reconstructed object only holds weak references.
48+
For example, a weak reference is reduced to
49+
``(weakref.ref, (Proxy(referent),))``.
50+
51+
A proxy is pickled as the wrapped object *obj*,
52+
which is unpickled in its place.
53+
*obj* must also be strongly referenced elsewhere in the same pickle;
54+
otherwise pickling raises :exc:`pickle.PicklingError`.
55+
56+
:func:`copy.copy` of a proxy returns *obj*,
57+
and :func:`copy.deepcopy` returns the deep copy of *obj*.
58+
59+
.. attribute:: obj
60+
61+
The wrapped object.
62+
63+
.. versionadded:: next
64+
65+
4266
Example
4367
-------
4468

‎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::

‎Doc/library/weakref.rst‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,10 @@ These have the same issues as the :meth:`WeakKeyDictionary.keyrefs` method.
276276

277277
A :class:`!WeakSet` can be pickled if the elements are strongly
278278
referenced elsewhere in the same pickle (see :class:`ref`).
279-
A copy or a deep copy shares the elements with the original;
280-
user-defined attributes are copied or deep-copied.
279+
A shallow copy contains the same elements as the original.
280+
A deep copy refers to the deep copies of the elements,
281+
so they must be deep-copied together with it;
282+
its user-defined attributes are deep-copied.
281283

282284
.. versionchanged:: 3.16
283285
:class:`!WeakSet` can now be pickled and copied.
@@ -314,7 +316,9 @@ These have the same issues as the :meth:`WeakKeyDictionary.keyrefs` method.
314316
A :class:`!WeakMethod` can be copied,
315317
and pickled if the object the method is bound to is strongly referenced
316318
elsewhere in the same pickle (see :class:`ref`).
317-
A copy or a deep copy is an equal weak method to the same object.
319+
A copy is an equal weak method bound to the same object.
320+
A deep copy is bound to the deep copy of the object,
321+
so it must be deep-copied together with it.
318322

319323
.. versionadded:: 3.4
320324

‎Doc/whatsnew/3.16.rst‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,17 @@ copy
249249
:gh:`155044`, :gh:`155041`, :gh:`155040`, and :gh:`155033`.)
250250

251251

252+
copyreg
253+
-------
254+
255+
* Add :class:`copyreg.Proxy`, a wrapper that is pickled as the wrapped object.
256+
Reduction functions can use it to pickle objects
257+
to which the reconstructed object only holds weak references.
258+
The wrapped object must be strongly referenced elsewhere in the same pickle;
259+
otherwise pickling raises :exc:`pickle.PicklingError`.
260+
(Contributed by Serhiy Storchaka in :gh:`74876`.)
261+
262+
252263
csv
253264
---
254265

‎Lib/_weakrefset.py‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# by abc.py to load everything else at startup.
44

55
from _weakref import ref
6+
from copyreg import Proxy
67
from types import GenericAlias
78

89
__all__ = ['WeakSet']
@@ -44,14 +45,13 @@ def __contains__(self, item):
4445
return wr in self.data
4546

4647
def __reduce__(self):
47-
# Pickle the elements as weak references; data and _remove are
48-
# rebuilt by the reconstructor. Copying shares the elements.
48+
# The elements must be strongly referenced elsewhere in the pickle.
49+
# data and _remove are rebuilt by the constructor.
4950
dict, slots = self.__getstate__()
5051
for name in ('data', '_remove'):
5152
slots.pop(name, None)
5253
state = (dict, slots) if dict or slots else None
53-
return (_restore_weakset, (self.__class__, [ref(item) for item in self]),
54-
state)
54+
return (self.__class__, ([Proxy(item) for item in self],), state)
5555

5656
def add(self, item):
5757
self.data.add(ref(item, self._remove))
@@ -62,6 +62,8 @@ def clear(self):
6262
def copy(self):
6363
return self.__class__(self)
6464

65+
__copy__ = copy
66+
6567
def pop(self):
6668
while True:
6769
try:
@@ -156,10 +158,3 @@ def __repr__(self):
156158
return repr(self.data)
157159

158160
__class_getitem__ = classmethod(GenericAlias)
159-
160-
161-
def _restore_weakset(cls, refs):
162-
self = cls.__new__(cls)
163-
WeakSet.__init__(self)
164-
self.update(item for r in refs for item in [r()] if item is not None)
165-
return self

‎Lib/copy.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class instances).
5151

5252
import types
5353
import weakref
54-
from copyreg import dispatch_table
54+
from copyreg import dispatch_table, Proxy
5555

5656
class Error(Exception):
5757
pass
@@ -71,6 +71,8 @@ def copy(x):
7171
return x
7272
if cls in _copy_builtin_containers:
7373
return cls.copy(x)
74+
if cls is Proxy:
75+
return x.obj
7476

7577

7678
if issubclass(cls, type):
@@ -221,6 +223,10 @@ def _deepcopy_method(x, memo): # Copy instance methods
221223
return type(x)(x.__func__, deepcopy(x.__self__, memo))
222224
d[types.MethodType] = _deepcopy_method
223225

226+
def _deepcopy_proxy(x, memo, deepcopy=deepcopy):
227+
return deepcopy(x.obj, memo)
228+
d[Proxy] = _deepcopy_proxy
229+
224230
del d
225231

226232
def _keep_alive(x, memo):

‎Lib/copyreg.py‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
C, not for instances of user-defined classes.
55
"""
66

7-
__all__ = ["pickle", "constructor",
7+
__all__ = ["pickle", "constructor", "Proxy",
88
"add_extension", "remove_extension", "clear_extension_cache"]
99

1010
dispatch_table = {}
@@ -23,6 +23,39 @@ def constructor(object):
2323
if not callable(object):
2424
raise TypeError("constructors must be callable")
2525

26+
class Proxy:
27+
"""Wrapper for an object that is pickled as a weak reference.
28+
29+
Pickling a Proxy pickles the wrapped object, which is unpickled in
30+
its place. Like the referent of a weak reference, the wrapped object
31+
must also be strongly referenced elsewhere in the same pickle,
32+
otherwise pickling fails. This lets a reduction function pickle
33+
objects that the reconstructed object will only refer to weakly.
34+
"""
35+
36+
__slots__ = ('obj',)
37+
38+
def __init_subclass__(cls, /, **kwargs):
39+
raise TypeError("type 'Proxy' is not an acceptable base type")
40+
41+
def __init__(self, obj):
42+
self.obj = obj
43+
44+
def __repr__(self):
45+
return f'{self.__class__.__qualname__}({self.obj!r})'
46+
47+
class _Reducer:
48+
# An object that is pickled and copied as the result of a call:
49+
# reduce is a (callable, args) pair returned from __reduce__().
50+
51+
__slots__ = ('_reduce',)
52+
53+
def __init__(self, reduce):
54+
self._reduce = reduce
55+
56+
def __reduce__(self):
57+
return self._reduce
58+
2659
# Example: provide pickling support for complex numbers.
2760

2861
def pickle_complex(c):
@@ -41,6 +74,21 @@ def pickle_super(obj):
4174

4275
pickle(super, pickle_super)
4376

77+
from _weakref import ref as _ref
78+
79+
# All dead weak references are interchangeable, so they are pickled as
80+
# references to this set. It is unpickled as a new set which dies with
81+
# the unpickler's memo, and all dead references as the same reference.
82+
_dead_referent = set()
83+
84+
def pickle_weakref(r):
85+
obj = r()
86+
if obj is None:
87+
return _ref, (_dead_referent,)
88+
return _ref, (Proxy(obj),)
89+
90+
pickle(_ref, pickle_weakref)
91+
4492
# Support for pickling new-style objects
4593

4694
def _reconstructor(cls, base, state):

‎Lib/pickle.py‎

Lines changed: 17 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
"""
2424

2525
from types import FunctionType
26-
from copyreg import dispatch_table
26+
from copyreg import dispatch_table, Proxy
2727
from copyreg import _extension_registry, _inverted_registry, _extension_cache
2828
from itertools import batched
2929
from functools import partial
@@ -32,7 +32,6 @@
3232
from struct import pack, unpack
3333
import io
3434
import codecs
35-
import weakref
3635
import _compat_pickle
3736

3837
__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
@@ -487,7 +486,7 @@ def __init__(self, file, protocol=None, *, fix_imports=True,
487486
self._write_large_bytes = self.framer.write_large_bytes
488487
self.memo = {}
489488
# Ids of objects reached so far only through weak references; any
490-
# left at the end of dump() is an error. See save_weakref.
489+
# left at the end of dump() is an error. See save_proxy.
491490
self._weak_only = set()
492491
self.proto = int(protocol)
493492
self.bin = protocol >= 1
@@ -591,6 +590,10 @@ def save(self, obj, save_persistent_id=True, weak=False):
591590
self.write(self.get(x[0]))
592591
return
593592

593+
if type(obj) is Proxy:
594+
self.save_proxy(obj)
595+
return
596+
594597
rv = NotImplemented
595598
reduce = getattr(self, "reducer_override", _NoValue)
596599
if reduce is not _NoValue:
@@ -1286,39 +1289,18 @@ def save_type(self, obj):
12861289
dispatch[FunctionType] = save_global
12871290
dispatch[type] = save_type
12881291

1289-
def save_weakref(self, obj):
1290-
# Reconstruct as weakref.ref(referent). The referent is saved
1291-
# *weakly* (no anchoring, see save()) and tagged weak-only only after
1292+
def save_proxy(self, obj):
1293+
# A Proxy is pickled as its wrapped object, saved *weakly* (no
1294+
# anchoring, see save()). The object is tagged weak-only only after
12921295
# its whole subtree, so a strong cycle inside it cannot anchor it.
1293-
referent = obj()
1294-
if referent is None:
1295-
# All dead references are interchangeable: pickle by name as the
1296-
# weakref._dead_ref singleton.
1297-
self.write(GLOBAL + b'weakref\n_dead_ref\n')
1298-
return
1299-
1300-
save = self.save
1301-
write = self.write
1302-
save(weakref.ref)
1303-
# A referent already in the memo is anchored or already tracked;
1304-
# otherwise it is tagged below, until a strong save of it.
1305-
anchored = id(referent) in self.memo
1306-
# Build the 1-tuple (referent,); TUPLE1 needs protocol 2.
1307-
if self.proto < 2:
1308-
write(MARK)
1309-
save(referent, weak=True)
1310-
if not anchored and id(referent) in self.memo:
1311-
self._weak_only.add(id(referent))
1312-
write(TUPLE1 if self.proto >= 2 else TUPLE)
1313-
write(REDUCE)
1314-
# The referent's subtree may have pickled this very (cached) weakref
1315-
# already; reuse the memoized one.
1316-
if id(obj) in self.memo:
1317-
write(POP + self.get(self.memo[id(obj)][0]))
1318-
else:
1319-
self.memoize(obj)
1320-
1321-
dispatch[weakref.ReferenceType] = save_weakref
1296+
# An object already in the memo is anchored or already tracked;
1297+
# otherwise it stays tagged until a strong save of it.
1298+
obj = obj.obj
1299+
i = id(obj)
1300+
anchored = i in self.memo
1301+
self.save(obj, weak=True)
1302+
if not anchored and i in self.memo:
1303+
self._weak_only.add(i)
13221304

13231305

13241306
# Unpickling machinery

‎Lib/test/pickletester.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1866,6 +1866,17 @@ def test_weakref_reused_pickler(self):
18661866
obj2, wr2 = pickle.loads(f.getvalue())
18671867
self.assertIs(wr2(), obj2)
18681868

1869+
def test_proxy_without_strong_ref(self):
1870+
obj = Object()
1871+
for proto in protocols:
1872+
with self.subTest(proto=proto):
1873+
self.assertRaises(pickle.PicklingError, self.dumps,
1874+
copyreg.Proxy(obj), proto)
1875+
# Another Proxy is not a strong reference.
1876+
self.assertRaises(pickle.PicklingError, self.dumps,
1877+
[copyreg.Proxy(obj), copyreg.Proxy(obj)],
1878+
proto)
1879+
18691880
def test_bad_reduce_result(self):
18701881
obj = REX([print, ()])
18711882
for proto in protocols:
@@ -3684,6 +3695,23 @@ def test_dead_weakref(self):
36843695
support.gc_collect()
36853696
self.assertIsNone(a())
36863697

3698+
def test_proxy(self):
3699+
# A Proxy is unpickled as the wrapped object.
3700+
obj = Object()
3701+
for proto in protocols:
3702+
with self.subTest(proto=proto):
3703+
x, y = self.loads(self.dumps([obj, copyreg.Proxy(obj)], proto))
3704+
self.assertIs(type(x), Object)
3705+
self.assertIs(y, x)
3706+
# Identity holds regardless of pickling order.
3707+
x, y = self.loads(self.dumps([copyreg.Proxy(obj), obj], proto))
3708+
self.assertIs(type(x), Object)
3709+
self.assertIs(y, x)
3710+
# Objects which are not memoized need no strong reference.
3711+
x = self.loads(self.dumps([copyreg.Proxy(None),
3712+
copyreg.Proxy(42)], proto))
3713+
self.assertEqual(x, [None, 42])
3714+
36873715
def test_newobj_overridden_new(self):
36883716
# Test that Python class with C implemented __new__ is pickleable
36893717
for proto in protocols:
@@ -5575,6 +5603,24 @@ def f():
55755603

55765604
self.assertIsNone(wr())
55775605

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+
55785624

55795625
class AbstractDispatchTableTests:
55805626

0 commit comments

Comments
 (0)