diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 23d9f3c9667d868..122957dc58f6c15 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -9,11 +9,13 @@ from test.support import os_helper from test.support import _2G from test.support import subTests +from test.support.script_helper import assert_python_ok import weakref import pickle import operator import struct import sys +import textwrap import array from array import _array_reconstructor as array_reconstructor @@ -35,6 +37,21 @@ def test_array_is_sequence(self): self.assertIsInstance(array.array("B"), collections.abc.MutableSequence) self.assertIsInstance(array.array("B"), collections.abc.Reversible) + @support.cpython_only + def test_module_init_mutablesequence_register_failure(self): + # gh-153210: Check that when collections.abc.MutableSequence is unavailable + # The refcount of ArrayType is decremented correctly. + # This test only catches the issue in a debug build. + script = textwrap.dedent(""" + import collections.abc + del collections.abc.MutableSequence + try: + import array + except AttributeError: + pass + """) + assert_python_ok("-c", script) + def test_bad_constructor(self): self.assertRaises(TypeError, array.array) self.assertRaises(TypeError, array.array, spam=42) diff --git a/Misc/NEWS.d/next/Library/2026-07-07-00-26-06.gh-issue-153210.HRwj-j.rst b/Misc/NEWS.d/next/Library/2026-07-07-00-26-06.gh-issue-153210.HRwj-j.rst new file mode 100644 index 000000000000000..ef3279fee8061e6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-07-00-26-06.gh-issue-153210.HRwj-j.rst @@ -0,0 +1,2 @@ +:mod:`array`: Fix incorrect handling of reference counts when errors occur +during module import diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c index 9f613927be63159..528d1b287612fef 100644 --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -3409,14 +3409,12 @@ array_modexec(PyObject *m) PyObject *mutablesequence = PyImport_ImportModuleAttrString( "collections.abc", "MutableSequence"); if (!mutablesequence) { - Py_DECREF((PyObject *)state->ArrayType); return -1; } PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O", (PyObject *)state->ArrayType); Py_DECREF(mutablesequence); if (!res) { - Py_DECREF((PyObject *)state->ArrayType); return -1; } Py_DECREF(res);