Py_DECREF
,你不需要打电话
PyErr_Fetch
.
Py\u减量
Py\u减量
,您可能需要自己处理事情。)
例如,
tp_finalize
,对象销毁的步骤之一,最有可能调用任意Python代码,
is explicitly responsible for saving and restoring an active exception
:
tp\U最终确定
因此,编写非平凡终结器的建议方法是:
static void
local_finalize(PyObject *self)
{
PyObject *error_type, *error_value, *error_traceback;
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
/* ... */
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
}
为了
__del__
方法,您可以在中看到相关的处理
slot_tp_finalize
:
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
/* Execute __del__ method, if any. */
del = lookup_maybe_method(self, &PyId___del__, &unbound);
if (del != NULL) {
res = call_unbound_noarg(unbound, del, self);
if (res == NULL)
PyErr_WriteUnraisable(del);
else
Py_DECREF(res);
Py_DECREF(del);
}
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
takes responsibility
if (*list != NULL) {
PyWeakReference *current = *list;
Py_ssize_t count = _PyWeakref_GetWeakrefCount(current);
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
if (count == 1) {
PyObject *callback = current->wr_callback;
current->wr_callback = NULL;
clear_weakref(current);
if (callback != NULL) {
if (((PyObject *)current)->ob_refcnt > 0)
handle_callback(current, callback);
Py_DECREF(callback);
}
}
else {
...
这么叫
Py\u减量
虽然设置了一个异常是很可怕的,而且您正在考虑它是很好的,但是只要对象销毁代码的行为正常,它应该是正常的。
皮耶尔
PyErr_Restore
完成后的异常状态。如果在清理过程中出现了另一个异常,可以将其链接起来(
awkward but possible
在C级),或用
PyErr_WriteUnraisable
PyErr_Clear
-或者是通过
PyErr\u还原
-将原始异常状态覆盖到它上面。