Skip to content

re.finditer() leaks reference cycles through its input #158095

Description

@YangSiJun528

Bug report

Bug description:

A reference cycle between a str subclass and its re.finditer() iterator is not collected:

import gc
import re
import weakref


class Text(str):
    pass


def create_cycle():
    text = Text("aaa")
    text.iterator = re.finditer("a+", text)
    return weakref.ref(text)


ref = create_cycle()
for _ in range(3):
    gc.collect()
print("collected:", ref() is None)

Expected: collected: True

Actual: collected: False

This also affects Pattern.scanner() and bytearray subclass inputs. For bytes-like inputs, PyObject_GetBuffer() acquires a strong reference stored in state.buffer.obj. scanner_traverse() omits the owned references in both state.string and state.buffer.obj.

AI assistance: Codex helped investigate, test, and draft this report.

CPython versions tested on:

CPython main branch, 3.14, 3.15

Operating systems tested on:

macOS

Linked PRs

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions