2

I am writing my own Python module and need some advice. Let's consider an example function in a module:

PyObject* my_func(PyObject *self, PyObject* args)
{
    PyObject* returnObj;
    try
    {
       returnObj = my_create_output();
    }
    catch(const std::exception& ex)
    {
        PyErr_SetString(PyExc_Exception, ex.what());
        returnObj = NULL;
    }
    return returnObj;
}

my_create_output function can raise different exceptions (also my own exceptions). returnObj is a big structure (for example, a list) and it may happen that my_create_output function will raise an exception when half of the output is already created. How should I delete the allocated objects in the catch block for such cases?

nobody
  • 19,814
  • 17
  • 56
  • 77
Samvel Hovsepyan
  • 639
  • 2
  • 6
  • 16

1 Answers1

2

my_create_output should handle the deallocation of everything it creates in the case of an exception, as a caller catching the exception has no way to access any of it.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Should I just use `Py_XDECREF` for allowing python interpreter to delete objects? – Samvel Hovsepyan Jul 03 '14 at 20:11
  • @SamvelHovsepyan: If your object is in a state where the ordinary destructor would clean it up properly, then `Py_XDECREF`ing it inside `my_create_output` would probably be the thing to do. – user2357112 Jul 03 '14 at 20:15