调用 PyErr_SetString 两次而不清除

问题描述 投票:0回答:1

我有一个 C++ 函数来解析 python 字符串:

std::string parse_string(PyObject* py_string) { 
  std::string out; 
  if (!PyString_Check(py_string)) { 
    PyErr_SetString(PyExc_TypeError,"expected a string");
    return out; 
  }
  out = PyString_AsString(py_string); 
  return out; 
}

我从 python 包装器调用该函数:

PyObject* some_func(PyObject* self, PyObject* args) { 
// ...
  std::string my_first_string = parse_string(first_py_string);
  if (PyErr_Occurred()) { 
    PyErr_SetString(PyExc_TypeError,"more verbose error for this string"); 
    return 0; 
  }
  std::string my_second_string = parse_string(second_py_string);
  if (PyErr_Occurred()) { 
    PyErr_SetString(PyExc_TypeError,"some other error for this string"); 
    return 0; 
  }
// ...
}

这将根据需要抛出一个 python 异常,但我担心再次调用

PyErr_SetString
来给出更详细的消息。会不会造成泄漏?

c++ exception cpython
1个回答
0
投票

根据Python扩展模式,可以在单个调用堆栈中多次设置异常。当你返回Python时,只会设置并抛出最后一个。

The other thing to note is that if there are multiple calls 
to PyErr_SetString only the last one counts:

static PyObject *_raise_error_overwrite(PyObject *module) {
    PyErr_SetString(PyExc_RuntimeError, "FORGOTTEN.");
    PyErr_SetString(PyExc_ValueError, "ERROR: _raise_error_overwrite()");
    assert(PyErr_Occurred());
    return NULL;
}
© www.soinside.com 2019 - 2024. All rights reserved.