Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does error_already_set in Boost.python do and how to handle exceptions similarly in Python C API

I have been working on a project where I want to remove the boost dependencies and replace it with the Python C API.

I spent some time understanding the Python C API and I saw this catch (error_already_set const &)

I read the boost docs but it explains where it is used. But I want to know why it is needed and how can I achieve the same functionality using the native Python C api.

like image 284
NVS Abhilash Avatar asked Mar 29 '17 12:03

NVS Abhilash


People also ask

What is boost in Python?

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler.

What are Python exceptions?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.


1 Answers

Boost throws error_already_set when a Python error has occurred. So if you see code like this:

try {
    bp::exec(bp::str("garbage code is garbage"));
} catch (const bp::error_already_set&) {
    // your code here to examine Python traceback etc.
}

you'll replace it with:

your_ptr<PyObject> res = PyRun_String("garbage code is garbage");
if (!res) {
    // your code here to examine Python traceback etc.
}

In other words, wherever you see catch(error_already_set), there you will likely want to do some error handling using whatever PyObject* or other value is involved to recognize when an error has occurred (and therefore you can examine the traceback, or convert it into a C++ exception).

like image 69
John Zwinck Avatar answered Oct 01 '22 11:10

John Zwinck