You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
copy.copy() and copy.deepcopy() of weakref.WeakSet create broken copies #162802
3.14bugs and security fixes3.15bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error
WeakSet.__reduce__() returns the instance __dict__ as its state. That dict holds the internal attributes, including data (the set of weak references) and _remove (the callback closure bound to the original set). copy uses the same reduction, so copies end up with the original's internal state.
copy.copy() creates a set that shares data with the original:
>>> import copy, weakref
>>> classA: pass
...
>>> a, b = A(), A()
>>> s = weakref.WeakSet([a])
>>> c = copy.copy(s)
>>> c.add(b)
>>> len(s)
2
copy.deepcopy() creates a new data set, but it holds the same weak reference objects, whose callbacks remove items from the original set, and it shares _remove with the original. Dead references therefore are never removed from the copy:
>>> s = weakref.WeakSet([a])
>>> d = copy.deepcopy(s)
>>> del a
>>> len(s), len(d), list(d)
(0, 1, [])
Items added to the copy later also get the original's callback.
This is a long-standing problem: earlier versions also returned the instance __dict__ with the same internal attributes. Pickling a WeakSet always fails (TypeError: cannot pickle 'weakref.ReferenceType' object) for the same reason.
In 3.16, this was fixed as part of gh-74876, which added support for copying and pickling weak references and weak containers. That is a significant new feature, so it cannot be backported.
For 3.14 and 3.15, there are two options:
Forbid copying: make copy.copy() and copy.deepcopy() of WeakSet raise TypeError, as pickling already does. The WeakSet.copy() method works correctly and can be used instead.
Fix copying: define __copy__() and __deepcopy__() that create correct copies. But that means implementing the 3.16 semantics of copying weak containers in a bugfix release, which is a new feature.
3.14bugs and security fixes3.15bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error
Activity