Re: How to forward a custom exception to Python

Felix Salfelder <[email protected]>
Newsgroups gmane.comp.programming.swig
Message-ID <[email protected]>
On Fri, Jan 31, 2020 at 05:14:49PM +0100, Lukáš Hrázký wrote:
> I'm having trouble defining a custom exception in a library and using
> it in Python bindings for the library generated by SWIG. I need to
> catch this exception in Python (as a user of the library) and handle it
> in a special way.

Hi Lukáš.

just some thoughts.

> * If I link the other modules against _error.so, and _error.so is in
>   LD_LIBRARY_PATH, it works. (this is not normally the case, so not a
>   good solution)

there is also runpath. if you have a (private/hidden) library in
/usr/lib/$yourpackage/liberror.so, you might be able to use it without
LD_LIBRARY_PATH. link with "--enable-new-dtags -rpath
/usr/lib/$yourpackage". (not sure how portable this is, but it should
work on linux).

> * If I link the other modules against _error.so and make sure the
>   mylib.error Python module is imported first, it works. (this is what
>   I have now, but the solution is a borderline hack and looks very
>   fragile)

make it look less like a hack...  _error.so does not have to be a
"module". It could be simpler to just put a single symbol into some
error.so, compiled from error.cc and linked with -shared.  you need to
include some simple header in both error.cc and _error.i.

> * If I don't link against _error.so and use:
>   import sys, os
>   sys.setdlopenflags(os.RTLD_NOW | os.RTLD_GLOBAL)

instead of linking all your modules against liberror, you could dlopen
the library from __init__.py using something like
ctypes.PyDLL("/some/liberror.so", mode=ctypes.RTLD_GLOBAL)

> How can I solve this? It seems to me like having a custom exception
> propagated to Python is a rather common use case and the "right" way to
> do error handling. I find it hard to believe I'm the first one to run
> into this.

Perhaps one way is to map your exceptions to the corresponding python
style exceptions. eg raise a ValueError if some number is out of range,
whichever way your library signals this.

(not saying there is not a case for custom exceptions.)

> This could obviously work if I only had a single Python
> module with all the SWIG bindings. But I don't really want that and
> SWIG documentation also recommends multiple modules.

I don't know. having multiple modules may be the right way, but not
necessarily the easiest.

hth
felix


_______________________________________________
Swig-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/swig-user
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.