Skip to content

Pickling a weakref.ref subclass with protocol 0 or 1 raises RecursionError #162644

Backlog

Description

@AlexxRussell

Bug report

Pickling a weakref.ref subclass with protocol 0 or 1 raises RecursionError on main (3.16.0a2+, tested on macOS):

import pickle, weakref

class R(weakref.ref):
    pass

class O:
    pass

o = O()
r = R(o)
pickle.dumps(r, 0)   # same with protocol 1
C pickler: RecursionError: Stack overflow (used 16320 kB)
pickle._Pickler (pure Python): RecursionError: maximum recursion depth exceeded

On main, protocols 2 to 5 raise TypeError: cannot pickle 'R' object. On 3.14.3, protocols 0 and 1 raise TypeError: cannot pickle 'ReferenceType' object. Protocols 0 and 1 should also raise TypeError.

This started with gh-74876 / GH-153818 (merged 21 October 2026), which made weak references picklable. Only main is affected.

For protocols 0 and 1, copyreg._reduce_ex() builds the state with base(self). Here base is weakref.ReferenceType, so the state is a new weak reference to the object being pickled. Pickling that reference pickles its referent, the same object again, without end.

I have a fix in copyreg._reduce_ex() with a test and can open a PR.

CPython versions tested on:

3.14, CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Nov 25, 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

    stdlibtype-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions