diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst index 94a55240b66598..6908c7b186f627 100644 --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -167,6 +167,13 @@ See :ref:`__slots__ documentation ` for details. Accessing an attribute of the proxy object after the referent is garbage collected raises :exc:`ReferenceError`. + A proxy can be pickled if the referent is strongly referenced elsewhere in + the same pickle (see :class:`ref`). + The unpickled proxy refers to the unpickled referent. + A shallow copy of a proxy is the proxy itself. + A deep copy refers to the deep copy of the referent, + so it must be deep-copied together with it. + .. versionchanged:: 3.8 Extended the operator support on proxy objects to include the matrix multiplication operators ``@`` and ``@=``. @@ -174,6 +181,10 @@ See :ref:`__slots__ documentation ` for details. .. versionchanged:: 3.16 Raise :exc:`!TypeError` if *callback* is not callable or ``None``. + .. versionchanged:: next + Proxies are now pickled and copied as proxies, + not as their referents. + .. function:: getweakrefcount(object) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 336171ca041f90..346e56c1bdf093 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -717,6 +717,11 @@ pickle :class:`!WeakMethod` and :class:`!WeakSet` can now also be copied. (Contributed by Serhiy Storchaka in :gh:`74876`.) +* Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied + as proxies, not as their referents. + The referent must be strongly referenced elsewhere in the same pickle. + (Contributed by Serhiy Storchaka in :gh:`62268`.) + quopri ------ @@ -1515,6 +1520,16 @@ that may require changes to your code. raises :exc:`io.UnsupportedOperation` unless buffering is disabled. (Contributed by An Long in :gh:`86768`.) +* Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied + as proxies, not as their referents. + Pickling a proxy now raises :exc:`pickle.PicklingError` + if the referent is not strongly referenced elsewhere in the same pickle, + and a deep copy of a proxy made without its referent + refers to a discarded copy. + To get the former behavior, pickle or copy the referent instead + of the proxy. + (Contributed by Serhiy Storchaka in :gh:`62268`.) + Build changes ============= diff --git a/Lib/copy.py b/Lib/copy.py index 56f66ce38737f4..f8843a51b853ea 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -51,6 +51,7 @@ class instances). import types import weakref +from _weakref import _getreferent from copyreg import dispatch_table, Proxy class Error(Exception): @@ -106,7 +107,8 @@ def copy(x): bytes, frozendict, frozenset, type, range, slice, property, types.BuiltinFunctionType, types.EllipsisType, types.NotImplementedType, types.FunctionType, types.CodeType, - weakref.ref, super}) + weakref.ref, weakref.ProxyType, weakref.CallableProxyType, + super}) _copy_builtin_containers = frozenset({list, dict, set, bytearray}) def deepcopy(x, memo=None): @@ -227,6 +229,13 @@ def _deepcopy_proxy(x, memo, deepcopy=deepcopy): return deepcopy(x.obj, memo) d[Proxy] = _deepcopy_proxy +def _deepcopy_weakproxy(x, memo, deepcopy=deepcopy, proxy=weakref.proxy): + obj = _getreferent(x) + if obj is None: + return x + return proxy(deepcopy(obj, memo)) +d[weakref.ProxyType] = d[weakref.CallableProxyType] = _deepcopy_weakproxy + del d def _keep_alive(x, memo): diff --git a/Lib/copyreg.py b/Lib/copyreg.py index a00abc3d925f58..05c8b3b1d7eee3 100644 --- a/Lib/copyreg.py +++ b/Lib/copyreg.py @@ -74,11 +74,14 @@ def pickle_super(obj): pickle(super, pickle_super) -from _weakref import ref as _ref - -# All dead weak references are interchangeable, so they are pickled as -# references to this set. It is unpickled as a new set which dies with -# the unpickler's memo, and all dead references as the same reference. +from _weakref import (ref as _ref, proxy as _proxy, ProxyType as _ProxyType, + CallableProxyType as _CallableProxyType, + _getreferent) + +# All dead weak references and proxies are interchangeable, so they are +# pickled as references to this set. It is unpickled as a new set which +# dies with the unpickler's memo, and all dead references as the same +# reference. _dead_referent = set() def pickle_weakref(r): @@ -89,6 +92,15 @@ def pickle_weakref(r): pickle(_ref, pickle_weakref) +def pickle_weakproxy(p): + obj = _getreferent(p) + if obj is None: + return _proxy, (_dead_referent,) + return _proxy, (Proxy(obj),) + +pickle(_ProxyType, pickle_weakproxy) +pickle(_CallableProxyType, pickle_weakproxy) + # Support for pickling new-style objects def _reconstructor(cls, base, state): diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index b9760b84fa4bcd..40d73677de19d2 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -3636,6 +3636,8 @@ def test_newobj_generic(self): self.assertEqual(x.__dict__, y.__dict__, detail) def test_newobj_proxies(self): + if self.py_version < (3, 16): + self.skipTest('not supported in Python < 3.16') # NEWOBJ should use the __class__ rather than the raw type classes = myclasses[:] # Cannot create weakproxies to these classes @@ -3652,9 +3654,10 @@ def test_newobj_proxies(self): x = C(C.sample) x.foo = 42 p = weakref.proxy(x) - s = self.dumps(p, proto) - y = self.loads(s) + s = self.dumps([p, x], proto) + p2, y = self.loads(s) self.assertEqual(type(y), type(x)) # rather than type(p) + self.assertIs(p2, weakref.proxy(y)) detail = (proto, C, B, x, y, type(y)) self.assertEqual(B(x), B(y), detail) self.assertEqual(x.__dict__, y.__dict__, detail) diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index 6509421aaa768e..1586d238936c71 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -48,6 +48,22 @@ def create_bound_method(): return C().method +def pickle_function(): + return 42 + + +class ProxyLoop: + # Holds a weak proxy to itself (gh-62268). + setstate_calls = 0 + + def __init__(self): + self.recursive = weakref.proxy(self) + + def __setstate__(self, state): + type(self).setstate_calls += 1 + self.__dict__.update(state) + + class WeakValueDictionaryWithSlots(weakref.WeakValueDictionary): __slots__ = ('x', 'y') @@ -1163,6 +1179,98 @@ def __del__(self): gc.collect() self.assertEqual(errors, []) + def test_getreferent(self): + from _weakref import _getreferent + obj = Object(1) + r = weakref.ref(obj) + p = weakref.proxy(obj) + self.assertIs(_getreferent(r), obj) + self.assertIs(_getreferent(p), obj) + self.assertRaises(TypeError, _getreferent, obj) + del obj + gc_collect() + self.assertIsNone(_getreferent(r)) + self.assertIsNone(_getreferent(p)) + + def test_pickle_proxy(self): + # A proxy is unpickled as a proxy to the restored object, + # regardless of pickling order. + obj = Object(1) + p = weakref.proxy(obj) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + obj2, p2 = pickle.loads(pickle.dumps([obj, p], proto)) + self.assertIs(type(p2), weakref.ProxyType) + self.assertIs(p2, weakref.proxy(obj2)) + p2, obj2 = pickle.loads(pickle.dumps([p, obj], proto)) + self.assertIs(p2, weakref.proxy(obj2)) + + def test_pickle_callable_proxy(self): + obj = pickle_function + p = weakref.proxy(obj) + self.assertIs(type(p), weakref.CallableProxyType) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + obj2, p2 = pickle.loads(pickle.dumps([obj, p], proto)) + self.assertIs(type(p2), weakref.CallableProxyType) + self.assertIs(p2, weakref.proxy(obj2)) + self.assertEqual(p2(), 42) + + def test_pickle_dead_proxy(self): + # A dead proxy stays dead. + obj = Object(1) + p = weakref.proxy(obj) + del obj + gc_collect() + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + p2 = pickle.loads(pickle.dumps(p, proto)) + gc_collect() + self.assertIsInstance(p2, weakref.ProxyTypes) + self.assertRaises(ReferenceError, getattr, p2, 'arg') + + def test_pickle_proxy_self_loop(self): + # The object is restored once (gh-62268). + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + data = pickle.dumps(ProxyLoop(), proto) + ProxyLoop.setstate_calls = 0 + obj = pickle.loads(data) + self.assertEqual(ProxyLoop.setstate_calls, 1) + self.assertIs(obj.recursive, weakref.proxy(obj)) + + def test_pickle_proxy_without_strong_ref(self): + obj = Object(1) + p = weakref.proxy(obj) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + self.assertRaises(pickle.PicklingError, pickle.dumps, p, proto) + + def test_copy_proxy(self): + obj = Object(1) + p = weakref.proxy(obj) + self.assertIs(copy.copy(p), p) + del obj + gc_collect() + self.assertIs(copy.copy(p), p) + + def test_deepcopy_proxy(self): + # A deep copy refers to the deep copy of the object, + # so it must be deep-copied together with it. + obj = Object(1) + p = weakref.proxy(obj) + obj2, p2 = copy.deepcopy([obj, p]) + self.assertIsNot(obj2, obj) + self.assertIs(p2, weakref.proxy(obj2)) + # Otherwise the copy of the object is discarded. + p2 = copy.deepcopy(p) + gc_collect() + self.assertRaises(ReferenceError, getattr, p2, 'arg') + # A dead proxy is not copied. + del obj + gc_collect() + self.assertIs(copy.deepcopy(p), p) + class SubclassableWeakrefTestCase(TestBase): diff --git a/Misc/NEWS.d/next/Library/2026-10-22-08-23-30.gh-issue-62268.SezALU.rst b/Misc/NEWS.d/next/Library/2026-10-22-08-23-30.gh-issue-62268.SezALU.rst new file mode 100644 index 00000000000000..fbb9ebd4b9eb9d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-22-08-23-30.gh-issue-62268.SezALU.rst @@ -0,0 +1,4 @@ +Weak reference proxies (:func:`weakref.proxy`) are now pickled and copied +as proxies, not as their referents. +The referent must be strongly referenced elsewhere in the same pickle; +otherwise pickling raises :exc:`pickle.PicklingError`. diff --git a/Modules/_weakref.c b/Modules/_weakref.c index 623252728554f7..9a13962e243fe4 100644 --- a/Modules/_weakref.c +++ b/Modules/_weakref.c @@ -109,6 +109,36 @@ _weakref_getweakrefs(PyObject *module, PyObject *object) } +/*[clinic input] +_weakref._getreferent + weakref: object + / + +Return the object referred to by a weak reference or proxy. + +Return None if the referent is no longer alive. +[clinic start generated code]*/ + +static PyObject * +_weakref__getreferent(PyObject *module, PyObject *weakref) +/*[clinic end generated code: output=0ee2af16dff9f385 input=1b02512a1c3189da]*/ +{ + if (!PyWeakref_Check(weakref)) { + PyErr_Format(PyExc_TypeError, + "expected a weak reference or proxy, not %T", weakref); + return NULL; + } + PyObject *obj; + if (PyWeakref_GetRef(weakref, &obj) < 0) { + return NULL; + } + if (obj == NULL) { + Py_RETURN_NONE; + } + return obj; +} + + /*[clinic input] _weakref.proxy @@ -135,6 +165,7 @@ weakref_functions[] = { _WEAKREF_GETWEAKREFCOUNT_METHODDEF _WEAKREF__REMOVE_DEAD_WEAKREF_METHODDEF _WEAKREF_GETWEAKREFS_METHODDEF + _WEAKREF__GETREFERENT_METHODDEF _WEAKREF_PROXY_METHODDEF {NULL, NULL, 0, NULL} }; diff --git a/Modules/clinic/_weakref.c.h b/Modules/clinic/_weakref.c.h index 8d7bc5dc936610..52d5ed40f3c841 100644 --- a/Modules/clinic/_weakref.c.h +++ b/Modules/clinic/_weakref.c.h @@ -76,6 +76,17 @@ PyDoc_STRVAR(_weakref_getweakrefs__doc__, #define _WEAKREF_GETWEAKREFS_METHODDEF \ {"getweakrefs", (PyCFunction)_weakref_getweakrefs, METH_O, _weakref_getweakrefs__doc__}, +PyDoc_STRVAR(_weakref__getreferent__doc__, +"_getreferent($module, weakref, /)\n" +"--\n" +"\n" +"Return the object referred to by a weak reference or proxy.\n" +"\n" +"Return None if the referent is no longer alive."); + +#define _WEAKREF__GETREFERENT_METHODDEF \ + {"_getreferent", (PyCFunction)_weakref__getreferent, METH_O, _weakref__getreferent__doc__}, + PyDoc_STRVAR(_weakref_proxy__doc__, "proxy($module, object, callback=None, /)\n" "--\n" @@ -112,4 +123,4 @@ _weakref_proxy(PyObject *module, PyObject *const *args, Py_ssize_t nargs) exit: return return_value; } -/*[clinic end generated code: output=60f59adc1dc9eab8 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=f3229d034d6fdd85 input=a9049054013a1b77]*/