Piero V.

Python custom exceptions in C(++) extensions

Python is a nice scripting language, but it has the fame of being difficult to embed and interact with existing projects.

Until now, I have been able to embed it in the software I work on with pybind11 and Binder (half of my MS degree thesis is about that), I had some problems, but I was able to solve most of them. But recently I have experienced a problem that is quite uncommon on the Internet: declaring a new exception in a native (C++/C module) with some custom methods/properties.

The existing proposal

I quickly looked on the Internet for the problem. The Python C API makes creating an exception type possible with PyObject *PyErr_NewException(const char *name, PyObject *bases, PyObject *dict): the first parameter is the name of the exception, in the modulename.ExceptionName format, the second parameter is the base or bases of the new exception (can be a PyType, or a tuple of PyTypes), and a dictionary of custom members and methods for the new type.

However both the second and third parameter can be left to NULL: in this case the new type will inherit from PyExc_Exception and will not have customizations. This is the majority of the cases, and by a search on the CPython code I could not find any reference that could use as an example on how to use the dict parameter. … [Leggi il resto]