Alan
Alan

Reputation: 2178

How should I handle an error in Python 2.7 in the initialization method for a C extension?

In Python 2.7 (which we need to support), the initialization function for a C/C++ extension should be declared with the PyMODINIT_FUNC macro, which effectively makes the function void. However, I'm not sure how we should handle errors that occurs during this function. We could throw a C++ exception within the function, but I'm not thrilled about that idea. Is there a better way?

Here's the background: In order to work around an architectural problem that we cannot address in a single release, we need to have the user call Python via a script that we provide rather than directly from the Python executable. By checking the process name, we can detect the situation where the user calls via the executable rather than the script. In this case, we would like to issue an error message and then terminate gracefully.

Upvotes: 1

Views: 59

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17761

You can use one of the PyErr_Set* methods.

Exceptions are always checked after calling init_module_name().

It's not explicitly stated in the documentation, but if you look at the examples, or if you read the source, you'll see that it is true.

Upvotes: 1

Related Questions