Skip to content

gh-162644: Fix infinite recursion when pickling a weakref.ref subclass with protocol 0 or 1 - #162666

Open
AlexxRussell wants to merge 1 commit into
python:mainfrom
AlexxRussell:gh-162644-pickle-weakref-subclass
Open

AlexxRussell wants to merge 1 commit into
python:mainfrom
AlexxRussell:gh-162644-pickle-weakref-subclass

Conversation

@AlexxRussell

@AlexxRussell AlexxRussell commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Since GH-153818, pickling an instance of a plain weakref.ref subclass with protocol 0 or 1 ends in RecursionError. copyreg._reduce_ex() puts weakref.ref(self) into the reduce arguments, and save_weakref() saves its referent, which is the instance being reduced and not in the memo yet, so the same steps repeat. In 3.14 this raised TypeError, as protocols 2 and higher still do.

save_weakref() now raises TypeError when the weak save of an object that is not in the memo leads straight back to a weak save of the same object and nothing has been memoized in between.

In the issue I wrote that I had a fix in copyreg._reduce_ex(). That one was wrong: object.__reduce__() always goes through _reduce_ex(), so raising there also broke subclasses that reuse the state from super().__reduce__(), which work in 3.14 and on main:

class R(weakref.ref):
    def __reduce__(self):
        _, _, *state = super().__reduce__()
        return (type(self), (self(),), *state)

Two things to know:

  • The check assumes that an object is reduced the same way each time during a dump. A __reduce__() that changes its answer between calls works on main and can raise TypeError now.
  • It also catches other objects whose reduce arguments contain a weak reference to the object itself. Those ended in RecursionError as well.

…ubclass with protocol 0 or 1

The pickler now raises TypeError when the weak save of an object leads
straight back to a weak save of the same object and nothing has been
memoized in between.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant