开发者

How to create a custom Python exception type in C extension?

I'm writing a Python module in C. I need to report errors that can't be described by built-in Python exceptions. I therefore wish to throw exceptions of my own type. The problem is, that Python policy is to derive all exceptions from BaseException class. I know how to create a derived type object (assigning to tp_base memeber), but I don't know how to obtain a reference to Bas开发者_开发问答eException type object. PyExc_BaseException is a reference to PyObject, representing a class, not a type object.

How do I throw custom Python exceptions from C code?


The easiest way to create a new exception type in C code is to call PyErr_NewException.


I managed to set tp_base by using (PyTypeObject*)PyExc_BaseException as the value, which results in my custom exception being properly inherited from BaseException.

There are some good hints in the CPython source code in exceptions.c.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜