Skip to content

copy.copy() and copy.deepcopy() of weakref.WeakSet create broken copies #162802

Backlog

Description

@serhiy-storchaka

Bug report

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
>>> class A: 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:

  1. 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.
  2. 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.

So I propose the first option.

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    3.14
    3.15
    on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.143.15stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions