Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Lib/test/test_opcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 7 additions & 2 deletions Python/specialize.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading