Python: Referring to an Exception Class Created with PyErr_NewException in an Extension Module

江枫思渺然 提交于 2020-01-03 00:00:11

问题


I am creating my own Python extension (using SWIG, but I hope that is not relevant).

In the C++ side of it, I am using PyErr_NewException to create a custom exception object.

// C++ - create a custom Python Exception class.

m = Py_InitModule((char *) "MyModule", SwigMethods);
g_pyMyErr = PyErr_NewException( "MyModule.MyErr", 0, 0 );
Py_INCREF(g_pyMyErr);
int result = PyModule_AddObject(m, "MyErr", g_pyMyErr);

The above code returns success values and I can throw the above exception successfully and catch it in the Python client code.

The problem is this: When I refer to "MyErr" in Python code I get an error saying "MyErr" is not defined.

// Python client code - catch the exception

from MyModule import *

try:
    causeException()
catch MyErr:  # Error: MyErr is not defined.
    pass
catch Exception:
    pass

EDIT: My current thinking is that maybe SWIG is altering (mangling) the names of things.


回答1:


You need to define the error then:

%{
  class MyErr {};
%}

Also, I would suggest adding this, so that you could catch the exceptions as MyModule.MyErr and not as MyModule._MyModule.MyErr (since that is how they will be generated by SWIG):

%pythoncode %{
  MyErr = _MyModule.MyErr
%}


来源:https://stackoverflow.com/questions/19916572/python-referring-to-an-exception-class-created-with-pyerr-newexception-in-an-ex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!