1

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.

bluedog
  • 935
  • 1
  • 8
  • 24
  • 2
    Does it work if you import the module itself with `import MyModule` then refer to `MyModule.MyErr`? It might be that your issue has to do with the `from MyModule import *`. If that's the issue, you probably need to add `MyErr` to `__all__`. – Blckknght Nov 12 '13 at 00:13
  • @Blckknght The "\_\_all\_\_" idea sounded promising, but didn't change the behavior unfortunately. – bluedog Nov 12 '13 at 00:24

1 Answers1

0

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
%}
Hermes
  • 756
  • 7
  • 10