Skip to content

Commit f11e438

Browse files
gh-62268: Pickle and copy weakref.proxy as a proxy
A weak reference proxy is now reduced to proxy(Proxy(referent)): it is unpickled as a proxy to the unpickled referent, which must be strongly referenced elsewhere in the same pickle. Formerly it was pickled as its referent. copy.copy() now returns the proxy itself, and copy.deepcopy() returns a proxy to the deep copy of the referent. Add the private function _weakref._getreferent() to get the referent of a proxy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 806d492 commit f11e438

9 files changed

Lines changed: 213 additions & 9 deletions

File tree

‎Doc/library/weakref.rst‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,24 @@ See :ref:`__slots__ documentation <slots>` for details.
167167
Accessing an attribute of the proxy object after the referent is
168168
garbage collected raises :exc:`ReferenceError`.
169169

170+
A proxy can be pickled if the referent is strongly referenced elsewhere in
171+
the same pickle (see :class:`ref`).
172+
The unpickled proxy refers to the unpickled referent.
173+
A shallow copy of a proxy is the proxy itself.
174+
A deep copy refers to the deep copy of the referent,
175+
so it must be deep-copied together with it.
176+
170177
.. versionchanged:: 3.8
171178
Extended the operator support on proxy objects to include the matrix
172179
multiplication operators ``@`` and ``@=``.
173180

174181
.. versionchanged:: 3.16
175182
Raise :exc:`!TypeError` if *callback* is not callable or ``None``.
176183

184+
.. versionchanged:: next
185+
Proxies are now pickled and copied as proxies,
186+
not as their referents.
187+
177188

178189
.. function:: getweakrefcount(object)
179190

‎Doc/whatsnew/3.16.rst‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,11 @@ pickle
717717
:class:`!WeakMethod` and :class:`!WeakSet` can now also be copied.
718718
(Contributed by Serhiy Storchaka in :gh:`74876`.)
719719

720+
* Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied
721+
as proxies, not as their referents.
722+
The referent must be strongly referenced elsewhere in the same pickle.
723+
(Contributed by Serhiy Storchaka in :gh:`62268`.)
724+
720725
quopri
721726
------
722727

@@ -1515,6 +1520,16 @@ that may require changes to your code.
15151520
raises :exc:`io.UnsupportedOperation` unless buffering is disabled.
15161521
(Contributed by An Long in :gh:`86768`.)
15171522

1523+
* Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied
1524+
as proxies, not as their referents.
1525+
Pickling a proxy now raises :exc:`pickle.PicklingError`
1526+
if the referent is not strongly referenced elsewhere in the same pickle,
1527+
and a deep copy of a proxy made without its referent
1528+
refers to a discarded copy.
1529+
To get the former behavior, pickle or copy the referent instead
1530+
of the proxy.
1531+
(Contributed by Serhiy Storchaka in :gh:`62268`.)
1532+
15181533

15191534
Build changes
15201535
=============

‎Lib/copy.py‎

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

5252
import types
5353
import weakref
54+
from _weakref import _getreferent
5455
from copyreg import dispatch_table, Proxy
5556

5657
class Error(Exception):
@@ -106,7 +107,8 @@ def copy(x):
106107
bytes, frozendict, frozenset, type, range, slice, property,
107108
types.BuiltinFunctionType, types.EllipsisType,
108109
types.NotImplementedType, types.FunctionType, types.CodeType,
109-
weakref.ref, super})
110+
weakref.ref, weakref.ProxyType, weakref.CallableProxyType,
111+
super})
110112
_copy_builtin_containers = frozenset({list, dict, set, bytearray})
111113

112114
def deepcopy(x, memo=None):
@@ -227,6 +229,13 @@ def _deepcopy_proxy(x, memo, deepcopy=deepcopy):
227229
return deepcopy(x.obj, memo)
228230
d[Proxy] = _deepcopy_proxy
229231

232+
def _deepcopy_weakproxy(x, memo, deepcopy=deepcopy, proxy=weakref.proxy):
233+
obj = _getreferent(x)
234+
if obj is None:
235+
return x
236+
return proxy(deepcopy(obj, memo))
237+
d[weakref.ProxyType] = d[weakref.CallableProxyType] = _deepcopy_weakproxy
238+
230239
del d
231240

232241
def _keep_alive(x, memo):

‎Lib/copyreg.py‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,14 @@ def pickle_super(obj):
7474

7575
pickle(super, pickle_super)
7676

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.
77+
from _weakref import (ref as _ref, proxy as _proxy, ProxyType as _ProxyType,
78+
CallableProxyType as _CallableProxyType,
79+
_getreferent)
80+
81+
# All dead weak references and proxies are interchangeable, so they are
82+
# pickled as references to this set. It is unpickled as a new set which
83+
# dies with the unpickler's memo, and all dead references as the same
84+
# reference.
8285
_dead_referent = set()
8386

8487
def pickle_weakref(r):
@@ -89,6 +92,15 @@ def pickle_weakref(r):
8992

9093
pickle(_ref, pickle_weakref)
9194

95+
def pickle_weakproxy(p):
96+
obj = _getreferent(p)
97+
if obj is None:
98+
return _proxy, (_dead_referent,)
99+
return _proxy, (Proxy(obj),)
100+
101+
pickle(_ProxyType, pickle_weakproxy)
102+
pickle(_CallableProxyType, pickle_weakproxy)
103+
92104
# Support for pickling new-style objects
93105

94106
def _reconstructor(cls, base, state):

‎Lib/test/pickletester.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3636,6 +3636,8 @@ def test_newobj_generic(self):
36363636
self.assertEqual(x.__dict__, y.__dict__, detail)
36373637

36383638
def test_newobj_proxies(self):
3639+
if self.py_version < (3, 16):
3640+
self.skipTest('not supported in Python < 3.16')
36393641
# NEWOBJ should use the __class__ rather than the raw type
36403642
classes = myclasses[:]
36413643
# Cannot create weakproxies to these classes
@@ -3652,9 +3654,10 @@ def test_newobj_proxies(self):
36523654
x = C(C.sample)
36533655
x.foo = 42
36543656
p = weakref.proxy(x)
3655-
s = self.dumps(p, proto)
3656-
y = self.loads(s)
3657+
s = self.dumps([p, x], proto)
3658+
p2, y = self.loads(s)
36573659
self.assertEqual(type(y), type(x)) # rather than type(p)
3660+
self.assertIs(p2, weakref.proxy(y))
36583661
detail = (proto, C, B, x, y, type(y))
36593662
self.assertEqual(B(x), B(y), detail)
36603663
self.assertEqual(x.__dict__, y.__dict__, detail)

‎Lib/test/test_weakref.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,22 @@ def create_bound_method():
4848
return C().method
4949

5050

51+
def pickle_function():
52+
return 42
53+
54+
55+
class ProxyLoop:
56+
# Holds a weak proxy to itself (gh-62268).
57+
setstate_calls = 0
58+
59+
def __init__(self):
60+
self.recursive = weakref.proxy(self)
61+
62+
def __setstate__(self, state):
63+
type(self).setstate_calls += 1
64+
self.__dict__.update(state)
65+
66+
5167
class WeakValueDictionaryWithSlots(weakref.WeakValueDictionary):
5268
__slots__ = ('x', 'y')
5369

@@ -1163,6 +1179,98 @@ def __del__(self):
11631179
gc.collect()
11641180
self.assertEqual(errors, [])
11651181

1182+
def test_getreferent(self):
1183+
from _weakref import _getreferent
1184+
obj = Object(1)
1185+
r = weakref.ref(obj)
1186+
p = weakref.proxy(obj)
1187+
self.assertIs(_getreferent(r), obj)
1188+
self.assertIs(_getreferent(p), obj)
1189+
self.assertRaises(TypeError, _getreferent, obj)
1190+
del obj
1191+
gc_collect()
1192+
self.assertIsNone(_getreferent(r))
1193+
self.assertIsNone(_getreferent(p))
1194+
1195+
def test_pickle_proxy(self):
1196+
# A proxy is unpickled as a proxy to the restored object,
1197+
# regardless of pickling order.
1198+
obj = Object(1)
1199+
p = weakref.proxy(obj)
1200+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1201+
with self.subTest(proto=proto):
1202+
obj2, p2 = pickle.loads(pickle.dumps([obj, p], proto))
1203+
self.assertIs(type(p2), weakref.ProxyType)
1204+
self.assertIs(p2, weakref.proxy(obj2))
1205+
p2, obj2 = pickle.loads(pickle.dumps([p, obj], proto))
1206+
self.assertIs(p2, weakref.proxy(obj2))
1207+
1208+
def test_pickle_callable_proxy(self):
1209+
obj = pickle_function
1210+
p = weakref.proxy(obj)
1211+
self.assertIs(type(p), weakref.CallableProxyType)
1212+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1213+
with self.subTest(proto=proto):
1214+
obj2, p2 = pickle.loads(pickle.dumps([obj, p], proto))
1215+
self.assertIs(type(p2), weakref.CallableProxyType)
1216+
self.assertIs(p2, weakref.proxy(obj2))
1217+
self.assertEqual(p2(), 42)
1218+
1219+
def test_pickle_dead_proxy(self):
1220+
# A dead proxy stays dead.
1221+
obj = Object(1)
1222+
p = weakref.proxy(obj)
1223+
del obj
1224+
gc_collect()
1225+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1226+
with self.subTest(proto=proto):
1227+
p2 = pickle.loads(pickle.dumps(p, proto))
1228+
gc_collect()
1229+
self.assertIsInstance(p2, weakref.ProxyTypes)
1230+
self.assertRaises(ReferenceError, getattr, p2, 'arg')
1231+
1232+
def test_pickle_proxy_self_loop(self):
1233+
# The object is restored once (gh-62268).
1234+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1235+
with self.subTest(proto=proto):
1236+
data = pickle.dumps(ProxyLoop(), proto)
1237+
ProxyLoop.setstate_calls = 0
1238+
obj = pickle.loads(data)
1239+
self.assertEqual(ProxyLoop.setstate_calls, 1)
1240+
self.assertIs(obj.recursive, weakref.proxy(obj))
1241+
1242+
def test_pickle_proxy_without_strong_ref(self):
1243+
obj = Object(1)
1244+
p = weakref.proxy(obj)
1245+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1246+
with self.subTest(proto=proto):
1247+
self.assertRaises(pickle.PicklingError, pickle.dumps, p, proto)
1248+
1249+
def test_copy_proxy(self):
1250+
obj = Object(1)
1251+
p = weakref.proxy(obj)
1252+
self.assertIs(copy.copy(p), p)
1253+
del obj
1254+
gc_collect()
1255+
self.assertIs(copy.copy(p), p)
1256+
1257+
def test_deepcopy_proxy(self):
1258+
# A deep copy refers to the deep copy of the object,
1259+
# so it must be deep-copied together with it.
1260+
obj = Object(1)
1261+
p = weakref.proxy(obj)
1262+
obj2, p2 = copy.deepcopy([obj, p])
1263+
self.assertIsNot(obj2, obj)
1264+
self.assertIs(p2, weakref.proxy(obj2))
1265+
# Otherwise the copy of the object is discarded.
1266+
p2 = copy.deepcopy(p)
1267+
gc_collect()
1268+
self.assertRaises(ReferenceError, getattr, p2, 'arg')
1269+
# A dead proxy is not copied.
1270+
del obj
1271+
gc_collect()
1272+
self.assertIs(copy.deepcopy(p), p)
1273+
11661274

11671275
class SubclassableWeakrefTestCase(TestBase):
11681276

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied
2+
as proxies, not as their referents.
3+
The referent must be strongly referenced elsewhere in the same pickle;
4+
otherwise pickling raises :exc:`pickle.PicklingError`.

‎Modules/_weakref.c‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,36 @@ _weakref_getweakrefs(PyObject *module, PyObject *object)
109109
}
110110

111111

112+
/*[clinic input]
113+
_weakref._getreferent
114+
weakref: object
115+
/
116+
117+
Return the object referred to by a weak reference or proxy.
118+
119+
Return None if the referent is no longer alive.
120+
[clinic start generated code]*/
121+
122+
static PyObject *
123+
_weakref__getreferent(PyObject *module, PyObject *weakref)
124+
/*[clinic end generated code: output=0ee2af16dff9f385 input=1b02512a1c3189da]*/
125+
{
126+
if (!PyWeakref_Check(weakref)) {
127+
PyErr_Format(PyExc_TypeError,
128+
"expected a weak reference or proxy, not %T", weakref);
129+
return NULL;
130+
}
131+
PyObject *obj;
132+
if (PyWeakref_GetRef(weakref, &obj) < 0) {
133+
return NULL;
134+
}
135+
if (obj == NULL) {
136+
Py_RETURN_NONE;
137+
}
138+
return obj;
139+
}
140+
141+
112142
/*[clinic input]
113143
114144
_weakref.proxy
@@ -135,6 +165,7 @@ weakref_functions[] = {
135165
_WEAKREF_GETWEAKREFCOUNT_METHODDEF
136166
_WEAKREF__REMOVE_DEAD_WEAKREF_METHODDEF
137167
_WEAKREF_GETWEAKREFS_METHODDEF
168+
_WEAKREF__GETREFERENT_METHODDEF
138169
_WEAKREF_PROXY_METHODDEF
139170
{NULL, NULL, 0, NULL}
140171
};

‎Modules/clinic/_weakref.c.h‎

Lines changed: 12 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)