gh-118473: Fix set_asyncgen_hooks not to be partially set when arguments are invalid (#118474)

This commit is contained in:
Jeong, YunWon 2024-05-07 09:02:52 +09:00 committed by GitHub
parent e272195b3e
commit 8d8275b0cf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 36 additions and 9 deletions

View File

@ -1788,6 +1788,21 @@ class SizeofTest(unittest.TestCase):
self.assertIsNone(old.finalizer)
firstiter = lambda *a: None
finalizer = lambda *a: None
with self.assertRaises(TypeError):
sys.set_asyncgen_hooks(firstiter=firstiter, finalizer="invalid")
cur = sys.get_asyncgen_hooks()
self.assertIsNone(cur.firstiter)
self.assertIsNone(cur.finalizer)
# gh-118473
with self.assertRaises(TypeError):
sys.set_asyncgen_hooks(firstiter="invalid", finalizer=finalizer)
cur = sys.get_asyncgen_hooks()
self.assertIsNone(cur.firstiter)
self.assertIsNone(cur.finalizer)
sys.set_asyncgen_hooks(firstiter=firstiter)
hooks = sys.get_asyncgen_hooks()
self.assertIs(hooks.firstiter, firstiter)
@ -1795,7 +1810,6 @@ class SizeofTest(unittest.TestCase):
self.assertIs(hooks.finalizer, None)
self.assertIs(hooks[1], None)
finalizer = lambda *a: None
sys.set_asyncgen_hooks(finalizer=finalizer)
hooks = sys.get_asyncgen_hooks()
self.assertIs(hooks.firstiter, firstiter)

View File

@ -0,0 +1 @@
Fix :func:`sys.set_asyncgen_hooks` not to be partially set when raising :exc:`TypeError`.

View File

@ -1399,12 +1399,6 @@ sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
Py_TYPE(finalizer)->tp_name);
return NULL;
}
if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
return NULL;
}
}
else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
return NULL;
}
if (firstiter && firstiter != Py_None) {
@ -1414,15 +1408,33 @@ sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
Py_TYPE(firstiter)->tp_name);
return NULL;
}
if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
}
PyObject *cur_finalizer = _PyEval_GetAsyncGenFinalizer();
if (finalizer && finalizer != Py_None) {
if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
return NULL;
}
}
else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
return NULL;
}
if (firstiter && firstiter != Py_None) {
if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
goto error;
}
}
else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
goto error;
}
Py_RETURN_NONE;
error:
_PyEval_SetAsyncGenFinalizer(cur_finalizer);
return NULL;
}
PyDoc_STRVAR(set_asyncgen_hooks_doc,