Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Doc/library/weakref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,24 @@ See :ref:`__slots__ documentation <slots>` 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 ``@=``.

.. 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)

Expand Down
15 changes: 15 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
------

Expand Down Expand Up @@ -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
=============
Expand Down
11 changes: 10 additions & 1 deletion Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class instances).

import types
import weakref
from _weakref import _getreferent
from copyreg import dispatch_table, Proxy

class Error(Exception):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
22 changes: 17 additions & 5 deletions Lib/copyreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand Down
7 changes: 5 additions & 2 deletions Lib/test/pickletester.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
108 changes: 108 additions & 0 deletions Lib/test/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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):

Expand Down
Original file line number Diff line number Diff line change
@@ -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`.
31 changes: 31 additions & 0 deletions Modules/_weakref.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}
};
Expand Down
13 changes: 12 additions & 1 deletion Modules/clinic/_weakref.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading