diff --git a/Lib/test/test_opcache.py b/Lib/test/test_opcache.py index 5f7c15f93a8332..429df79db93f6e 100644 --- a/Lib/test/test_opcache.py +++ b/Lib/test/test_opcache.py @@ -562,6 +562,42 @@ def instantiate(): with self.assertRaises(TypeError): instantiate() + @requires_jit_disabled + @requires_specialization + def test_abstract_class_is_not_instantiated(self): + class Abstract: + def __init__(self): + pass + Abstract.__abstractmethods__ = frozenset({"f"}) + + @reset_code + def instantiate(): + return Abstract() + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + with self.assertRaises(TypeError): + instantiate() + self.assert_no_opcode(instantiate, "CALL_ALLOC_AND_ENTER_INIT") + + # A class made abstract after its call was specialized. + class Later: + def __init__(self): + pass + + @reset_code + def instantiate_later(): + return Later() + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + instantiate_later() + self.assert_specialized(instantiate_later, "CALL_ALLOC_AND_ENTER_INIT") + Later.__abstractmethods__ = frozenset({"f"}) + # Run past the cooldown, so that the call is specialized again. + for _ in range(_testinternalcapi.SPECIALIZATION_COOLDOWN): + with self.assertRaises(TypeError): + instantiate_later() + self.assert_no_opcode(instantiate_later, "CALL_ALLOC_AND_ENTER_INIT") + def test_recursion_check_for_general_calls(self): def test(default=None): return test() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-23-17-19.gh-issue-162600.5olPVw.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-23-17-19.gh-issue-162600.5olPVw.rst new file mode 100644 index 00000000000000..b67d4d02d64475 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-23-17-19.gh-issue-162600.5olPVw.rst @@ -0,0 +1,3 @@ +Fix a class with ``__abstractmethods__`` assigned directly, without +:class:`abc.ABCMeta`, being instantiated instead of raising :exc:`TypeError` +when the same call is executed more than once. diff --git a/Python/specialize.c b/Python/specialize.c index b5cf4ebc31142a..03a1958f446eaf 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -1692,8 +1692,13 @@ specialize_class_call(PyObject *callable, _Py_CODEUNIT *instr, int nargs) Py_XDECREF(init); return -1; } - if (init != NULL && _PyType_CacheInitForSpecialization( - (PyHeapTypeObject *)tp, init, tp_version)) { + /* CALL_ALLOC_AND_ENTER_INIT skips object_new()'s abstract check. + Check after the lookup so a concurrent change invalidates + tp_version. */ + if (init != NULL && !(tp->tp_flags & Py_TPFLAGS_IS_ABSTRACT) && + _PyType_CacheInitForSpecialization( + (PyHeapTypeObject *)tp, init, tp_version)) + { _PyCallCache *cache = (_PyCallCache *)(instr + 1); write_u32(cache->func_version, tp_version); specialize(instr, CALL_ALLOC_AND_ENTER_INIT);