dataclasses classes are not garbage-collected
Summary
dataclass classes and their generated __init__ methods remain alive in RustPython after all external strong references are dropped and gc.collect() is called.
import gc
import weakref
from dataclasses import dataclass
def create():
@dataclass
class Example:
value: int
return weakref.ref(Example), weakref.ref(Example.__init__)
class_ref, init_ref = create()
for _ in range(3):
gc.collect()
print("class collected:", class_ref() is None)
print("__init__ collected:", init_ref() is None)Expected
CPython 3.14.6:
class collected: True
__init__ collected: TrueActual
RustPython 803520930:
class collected: False
__init__ collected: FalseCreating 100 new dataclass classes per batch, with three full collections after each batch, left 100, 200, and 300 classes and generated __init__ methods alive in RustPython. CPython retained none. Instances were collected in both interpreters.
The generated __init__.__annotate__ captures the class, forming a cycle through its closure. PyFunction::traverse does not visit its owned annotate field, leaving this reference unaccounted for during cycle detection. As a diagnostic control, setting Example.__init__.__annotate__ = None before dropping the class allowed both the class and __init__ to be collected in RustPython.
Python Documentation
dataclasses.dataclass.function.__annotate__.- CPython's
func_traversevisitsfunc_annotate.
AI assistance: Codex (gpt-6-astra) investigated the code, prepared and ran the reproductions, compared the results with CPython, and drafted this report.
Source: RustPython/RustPython