diff --git a/Lib/test/test_structseq.py b/Lib/test/test_structseq.py index 74506fc54de50e7..0f75cd236d32426 100644 --- a/Lib/test/test_structseq.py +++ b/Lib/test/test_structseq.py @@ -365,5 +365,10 @@ def test_replace_gc_tracked(self): self.assertTrue(gc.is_tracked(replaced_struct)) + def test_gc_tracked(self): + # PyStructSequence objects created via C API or Python should be GC-tracked + self.assertTrue(gc.is_tracked(time.gmtime())) + self.assertTrue(gc.is_tracked(os.stat(__file__))) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-09-08-15-55-00.gh-issue-157176.yZ8a1B.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-08-15-55-00.gh-issue-157176.yZ8a1B.rst new file mode 100644 index 000000000000000..a54dfab6a811f1e --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-08-15-55-00.gh-issue-157176.yZ8a1B.rst @@ -0,0 +1 @@ +Fix GC tracking for :class:`!PyStructSequence` instances created via :c:func:`PyStructSequence_New`. Patch by Shamil Abdulaev. diff --git a/Objects/structseq.c b/Objects/structseq.c index 9130fe6a133b1e4..7be74e1c01094d2 100644 --- a/Objects/structseq.c +++ b/Objects/structseq.c @@ -84,6 +84,7 @@ PyStructSequence_New(PyTypeObject *type) for (i = 0; i < size; i++) obj->ob_item[i] = NULL; + _PyObject_GC_TRACK(obj); return (PyObject*)obj; } @@ -265,7 +266,6 @@ structseq_new_impl(PyTypeObject *type, PyObject *arg, PyObject *dict) } } - _PyObject_GC_TRACK(res); return (PyObject*) res; } @@ -449,7 +449,6 @@ structseq_replace(PyObject *op, PyObject *args, PyObject *kwargs) } } - _PyObject_GC_TRACK(result); return (PyObject *)result; error: