gh-116437: Use new C API PyDict_Pop() to simplify the code (GH-116438)

This commit is contained in:
Serhiy Storchaka 2024-03-07 11:21:08 +02:00 committed by GitHub
parent 882fcede83
commit 72d3cc94cd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 116 additions and 119 deletions

View File

@ -2045,12 +2045,22 @@ static PyObject *
swap_current_task(asyncio_state *state, PyObject *loop, PyObject *task) swap_current_task(asyncio_state *state, PyObject *loop, PyObject *task)
{ {
PyObject *prev_task; PyObject *prev_task;
if (task == Py_None) {
if (PyDict_Pop(state->current_tasks, loop, &prev_task) < 0) {
return NULL;
}
if (prev_task == NULL) {
Py_RETURN_NONE;
}
return prev_task;
}
Py_hash_t hash; Py_hash_t hash;
hash = PyObject_Hash(loop); hash = PyObject_Hash(loop);
if (hash == -1) { if (hash == -1) {
return NULL; return NULL;
} }
prev_task = _PyDict_GetItem_KnownHash(state->current_tasks, loop, hash); prev_task = _PyDict_GetItem_KnownHash(state->current_tasks, loop, hash);
if (prev_task == NULL) { if (prev_task == NULL) {
if (PyErr_Occurred()) { if (PyErr_Occurred()) {
@ -2059,22 +2069,12 @@ swap_current_task(asyncio_state *state, PyObject *loop, PyObject *task)
prev_task = Py_None; prev_task = Py_None;
} }
Py_INCREF(prev_task); Py_INCREF(prev_task);
if (_PyDict_SetItem_KnownHash(state->current_tasks, loop, task, hash) == -1) {
if (task == Py_None) { Py_DECREF(prev_task);
if (_PyDict_DelItem_KnownHash(state->current_tasks, loop, hash) == -1) { return NULL;
goto error;
}
} else {
if (_PyDict_SetItem_KnownHash(state->current_tasks, loop, task, hash) == -1) {
goto error;
}
} }
return prev_task; return prev_task;
error:
Py_DECREF(prev_task);
return NULL;
} }
/* ----- Task */ /* ----- Task */

View File

@ -1606,10 +1606,12 @@ _csv_unregister_dialect_impl(PyObject *module, PyObject *name)
/*[clinic end generated code: output=0813ebca6c058df4 input=6b5c1557bf60c7e7]*/ /*[clinic end generated code: output=0813ebca6c058df4 input=6b5c1557bf60c7e7]*/
{ {
_csvstate *module_state = get_csv_state(module); _csvstate *module_state = get_csv_state(module);
if (PyDict_DelItem(module_state->dialects, name) < 0) { int rc = PyDict_Pop(module_state->dialects, name, NULL);
if (PyErr_ExceptionMatches(PyExc_KeyError)) { if (rc < 0) {
PyErr_Format(module_state->error_obj, "unknown dialect"); return NULL;
} }
if (rc == 0) {
PyErr_Format(module_state->error_obj, "unknown dialect");
return NULL; return NULL;
} }
Py_RETURN_NONE; Py_RETURN_NONE;

View File

@ -372,33 +372,27 @@ element_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject* static PyObject*
get_attrib_from_keywords(PyObject *kwds) get_attrib_from_keywords(PyObject *kwds)
{ {
PyObject *attrib_str = PyUnicode_FromString("attrib"); PyObject *attrib;
if (attrib_str == NULL) { if (PyDict_PopString(kwds, "attrib", &attrib) < 0) {
return NULL; return NULL;
} }
PyObject *attrib = PyDict_GetItemWithError(kwds, attrib_str);
if (attrib) { if (attrib) {
/* If attrib was found in kwds, copy its value and remove it from /* If attrib was found in kwds, copy its value and remove it from
* kwds * kwds
*/ */
if (!PyDict_Check(attrib)) { if (!PyDict_Check(attrib)) {
Py_DECREF(attrib_str);
PyErr_Format(PyExc_TypeError, "attrib must be dict, not %.100s", PyErr_Format(PyExc_TypeError, "attrib must be dict, not %.100s",
Py_TYPE(attrib)->tp_name); Py_TYPE(attrib)->tp_name);
Py_DECREF(attrib);
return NULL; return NULL;
} }
attrib = PyDict_Copy(attrib); Py_SETREF(attrib, PyDict_Copy(attrib));
if (attrib && PyDict_DelItem(kwds, attrib_str) < 0) {
Py_SETREF(attrib, NULL);
}
} }
else if (!PyErr_Occurred()) { else {
attrib = PyDict_New(); attrib = PyDict_New();
} }
Py_DECREF(attrib_str);
if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) { if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) {
Py_DECREF(attrib); Py_DECREF(attrib);
return NULL; return NULL;

View File

@ -1262,13 +1262,9 @@ _localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
/* If the thread-local object is still alive and not being cleared, /* If the thread-local object is still alive and not being cleared,
remove the corresponding local dict */ remove the corresponding local dict */
if (self->dummies != NULL) { if (self->dummies != NULL) {
PyObject *ldict; if (PyDict_Pop(self->dummies, dummyweakref, NULL) < 0) {
ldict = PyDict_GetItemWithError(self->dummies, dummyweakref);
if (ldict != NULL) {
PyDict_DelItem(self->dummies, dummyweakref);
}
if (PyErr_Occurred())
PyErr_WriteUnraisable((PyObject*)self); PyErr_WriteUnraisable((PyObject*)self);
}
} }
Py_DECREF(self); Py_DECREF(self);
Py_RETURN_NONE; Py_RETURN_NONE;

View File

@ -17566,11 +17566,11 @@ posixmodule_exec(PyObject *m)
return -1; return -1;
} }
if (PyDict_DelItemString(dct, "pwritev") == -1) { if (PyDict_PopString(dct, "pwritev", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "preadv") == -1) { if (PyDict_PopString(dct, "preadv", NULL) < 0) {
PyErr_Clear(); return -1;
} }
} }
#endif #endif

View File

@ -1928,20 +1928,20 @@ time_exec(PyObject *module)
return -1; return -1;
} }
if (PyDict_DelItemString(dct, "clock_gettime") == -1) { if (PyDict_PopString(dct, "clock_gettime", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "clock_gettime_ns") == -1) { if (PyDict_PopString(dct, "clock_gettime_ns", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "clock_settime") == -1) { if (PyDict_PopString(dct, "clock_settime", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "clock_settime_ns") == -1) { if (PyDict_PopString(dct, "clock_settime_ns", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "clock_getres") == -1) { if (PyDict_PopString(dct, "clock_getres", NULL) < 0) {
PyErr_Clear(); return -1;
} }
} }
#endif #endif
@ -1951,11 +1951,11 @@ time_exec(PyObject *module)
} else { } else {
PyObject* dct = PyModule_GetDict(module); PyObject* dct = PyModule_GetDict(module);
if (PyDict_DelItemString(dct, "thread_time") == -1) { if (PyDict_PopString(dct, "thread_time", NULL) < 0) {
PyErr_Clear(); return -1;
} }
if (PyDict_DelItemString(dct, "thread_time_ns") == -1) { if (PyDict_PopString(dct, "thread_time_ns", NULL) < 0) {
PyErr_Clear(); return -1;
} }
} }
#endif #endif

View File

@ -1004,9 +1004,13 @@ module_set_annotations(PyModuleObject *m, PyObject *value, void *Py_UNUSED(ignor
} }
else { else {
/* delete */ /* delete */
ret = PyDict_DelItem(dict, &_Py_ID(__annotations__)); ret = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
if (ret < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) { if (ret == 0) {
PyErr_SetString(PyExc_AttributeError, "__annotations__"); PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__annotations__));
ret = -1;
}
else if (ret > 0) {
ret = 0;
} }
} }

View File

@ -1236,20 +1236,22 @@ type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
} }
else { else {
abstract = 0; abstract = 0;
res = PyDict_DelItem(dict, &_Py_ID(__abstractmethods__)); res = PyDict_Pop(dict, &_Py_ID(__abstractmethods__), NULL);
if (res && PyErr_ExceptionMatches(PyExc_KeyError)) { if (res == 0) {
PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__abstractmethods__)); PyErr_SetObject(PyExc_AttributeError, &_Py_ID(__abstractmethods__));
return -1; return -1;
} }
} }
if (res == 0) { if (res < 0) {
PyType_Modified(type); return -1;
if (abstract)
type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
else
type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
} }
return res;
PyType_Modified(type);
if (abstract)
type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
else
type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
return 0;
} }
static PyObject * static PyObject *
@ -1606,16 +1608,18 @@ type_set_annotations(PyTypeObject *type, PyObject *value, void *context)
result = PyDict_SetItem(dict, &_Py_ID(__annotations__), value); result = PyDict_SetItem(dict, &_Py_ID(__annotations__), value);
} else { } else {
/* delete */ /* delete */
result = PyDict_DelItem(dict, &_Py_ID(__annotations__)); result = PyDict_Pop(dict, &_Py_ID(__annotations__), NULL);
if (result < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) { if (result == 0) {
PyErr_SetString(PyExc_AttributeError, "__annotations__"); PyErr_SetString(PyExc_AttributeError, "__annotations__");
return -1;
} }
} }
if (result < 0) {
if (result == 0) { return -1;
PyType_Modified(type);
} }
return result;
PyType_Modified(type);
return 0;
} }
static PyObject * static PyObject *

View File

@ -1077,20 +1077,20 @@ ast_type_reduce(PyObject *self, PyObject *unused)
if (!name) { if (!name) {
goto cleanup; goto cleanup;
} }
PyObject *value = PyDict_GetItemWithError(remaining_dict, name); PyObject *value;
int rc = PyDict_Pop(remaining_dict, name, &value);
Py_DECREF(name);
if (rc < 0) {
goto cleanup;
}
if (!value) { if (!value) {
if (PyErr_Occurred()) {
goto cleanup;
}
break; break;
} }
if (PyList_Append(positional_args, value) < 0) { rc = PyList_Append(positional_args, value);
Py_DECREF(value);
if (rc < 0) {
goto cleanup; goto cleanup;
} }
if (PyDict_DelItem(remaining_dict, name) < 0) {
goto cleanup;
}
Py_DECREF(name);
} }
PyObject *args_tuple = PyList_AsTuple(positional_args); PyObject *args_tuple = PyList_AsTuple(positional_args);
if (!args_tuple) { if (!args_tuple) {

18
Python/Python-ast.c generated
View File

@ -5223,20 +5223,20 @@ ast_type_reduce(PyObject *self, PyObject *unused)
if (!name) { if (!name) {
goto cleanup; goto cleanup;
} }
PyObject *value = PyDict_GetItemWithError(remaining_dict, name); PyObject *value;
int rc = PyDict_Pop(remaining_dict, name, &value);
Py_DECREF(name);
if (rc < 0) {
goto cleanup;
}
if (!value) { if (!value) {
if (PyErr_Occurred()) {
goto cleanup;
}
break; break;
} }
if (PyList_Append(positional_args, value) < 0) { rc = PyList_Append(positional_args, value);
Py_DECREF(value);
if (rc < 0) {
goto cleanup; goto cleanup;
} }
if (PyDict_DelItem(remaining_dict, name) < 0) {
goto cleanup;
}
Py_DECREF(name);
} }
PyObject *args_tuple = PyList_AsTuple(positional_args); PyObject *args_tuple = PyList_AsTuple(positional_args);
if (!args_tuple) { if (!args_tuple) {

View File

@ -140,13 +140,10 @@ builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,
goto error; goto error;
} }
if (PyDict_GetItemRef(mkw, &_Py_ID(metaclass), &meta) < 0) { if (PyDict_Pop(mkw, &_Py_ID(metaclass), &meta) < 0) {
goto error; goto error;
} }
if (meta != NULL) { if (meta != NULL) {
if (PyDict_DelItem(mkw, &_Py_ID(metaclass)) < 0) {
goto error;
}
/* metaclass is explicitly given, check if it's indeed a class */ /* metaclass is explicitly given, check if it's indeed a class */
isclass = PyType_Check(meta); isclass = PyType_Check(meta);
} }

View File

@ -1307,14 +1307,14 @@ dummy_func(
inst(DELETE_GLOBAL, (--)) { inst(DELETE_GLOBAL, (--)) {
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg); PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
int err; int err = PyDict_Pop(GLOBALS(), name, NULL);
err = PyDict_DelItem(GLOBALS(), name);
// Can't use ERROR_IF here. // Can't use ERROR_IF here.
if (err != 0) { if (err < 0) {
if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { GOTO_ERROR(error);
_PyEval_FormatExcCheckArg(tstate, PyExc_NameError, }
NAME_ERROR_MSG, name); if (err == 0) {
} _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
NAME_ERROR_MSG, name);
GOTO_ERROR(error); GOTO_ERROR(error);
} }
} }

View File

@ -1167,14 +1167,14 @@
case _DELETE_GLOBAL: { case _DELETE_GLOBAL: {
oparg = CURRENT_OPARG(); oparg = CURRENT_OPARG();
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg); PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
int err; int err = PyDict_Pop(GLOBALS(), name, NULL);
err = PyDict_DelItem(GLOBALS(), name);
// Can't use ERROR_IF here. // Can't use ERROR_IF here.
if (err != 0) { if (err < 0) {
if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { GOTO_ERROR(error);
_PyEval_FormatExcCheckArg(tstate, PyExc_NameError, }
NAME_ERROR_MSG, name); if (err == 0) {
} _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
NAME_ERROR_MSG, name);
GOTO_ERROR(error); GOTO_ERROR(error);
} }
break; break;

View File

@ -2368,14 +2368,14 @@
next_instr += 1; next_instr += 1;
INSTRUCTION_STATS(DELETE_GLOBAL); INSTRUCTION_STATS(DELETE_GLOBAL);
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg); PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
int err; int err = PyDict_Pop(GLOBALS(), name, NULL);
err = PyDict_DelItem(GLOBALS(), name);
// Can't use ERROR_IF here. // Can't use ERROR_IF here.
if (err != 0) { if (err < 0) {
if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { GOTO_ERROR(error);
_PyEval_FormatExcCheckArg(tstate, PyExc_NameError, }
NAME_ERROR_MSG, name); if (err == 0) {
} _PyEval_FormatExcCheckArg(tstate, PyExc_NameError,
NAME_ERROR_MSG, name);
GOTO_ERROR(error); GOTO_ERROR(error);
} }
DISPATCH(); DISPATCH();

View File

@ -452,7 +452,7 @@ _PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
v = run_pyc_file(pyc_fp, dict, dict, flags); v = run_pyc_file(pyc_fp, dict, dict, flags);
} else { } else {
/* When running from stdin, leave __main__.__loader__ alone */ /* When running from stdin, leave __main__.__loader__ alone */
if (PyUnicode_CompareWithASCIIString(filename, "<stdin>") != 0 && if ((!PyUnicode_Check(filename) || !PyUnicode_EqualToUTF8(filename, "<stdin>")) &&
set_main_loader(dict, filename, "SourceFileLoader") < 0) { set_main_loader(dict, filename, "SourceFileLoader") < 0) {
fprintf(stderr, "python: failed to set __main__.__loader__\n"); fprintf(stderr, "python: failed to set __main__.__loader__\n");
ret = -1; ret = -1;
@ -472,11 +472,11 @@ _PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
done: done:
if (set_file_name) { if (set_file_name) {
if (PyDict_DelItemString(dict, "__file__")) { if (PyDict_PopString(dict, "__file__", NULL) < 0) {
PyErr_Clear(); PyErr_Print();
} }
if (PyDict_DelItemString(dict, "__cached__")) { if (PyDict_PopString(dict, "__cached__", NULL) < 0) {
PyErr_Clear(); PyErr_Print();
} }
} }
Py_XDECREF(main_module); Py_XDECREF(main_module);