From: Amaury F. d'A. <ama...@gm...> - 2007-03-26 11:47:57
|
Hello, 2007/3/24, Olly Betts wrote: > Replying to the swig-devel list, since this is discussing a change to > SWIG itself... > > On 2007-03-09, Richard Boulton <ri...@le...> wrote: > > I've recently converted a project using Swig (actually, Xapian) to use > > custom exception types for the Python bindings, rather than using the > > standard python exception types. I've got this all working nicely, > > except for one issue: I can't make (the Python proxy classes for) my > > custom exception types inherit from the standard Python Exception class > > (which all exceptions thrown in python should inherit from). > > Looking at the python docs, the nearest to a requirement I can find is > section 8.5 here: > > http://docs.python.org/tut/node10.html > > "Exceptions should typically be derived from the Exception class, > either directly or indirectly." > > To me "should typically" suggests a somewhat weaker requirement that RFC > 2119's "SHOULD" (http://www.ietf.org/rfc/rfc2119.txt) though I don't > see a situation where it's useful not to follow this recommendation. It > certainly seems that this is desirable default behaviour, though maybe > there needs to be a way to override. This is not only desirable, it will be enforced in future releases of python: See http://www.python.org/dev/peps/pep-0352. > > In the generated python code, I find the line: > > "class Error:" > > > > and I would like to change this somehow to: > > "class Error(Exception):" > > > > Is there any way to tell Swig that the proxy class for a C++ class > > should inherit from a specific python class? Or is there any other way > > that I can get swig to do what I want? > > For Xapian, we could just run sed over the wrapper code which SWIG > generates to fix this up, at least for now. > > I don't see a nice way to do it with SWIG. It might be possible to > lie to SWIG and claim the C++ Xapian::Error class inherits from an > unspecified Exception class, but even if that works I think I prefer > fixing up the generated code with sed. > > > (In theory, I wish that the %exceptionclass tag on a class would be > > observed and used automatically to ensure that the corresponding proxy > > class has the standard "Exception" class somewhere in it's ancestors - > > but that's not currently implemented. Perhaps that would be a useful > > feature for python?) > > This sounds good to me. What do the SWIG/Python experts think? > You could implement this with a __metaclass__. something like this: (warning: not tested at all) %pythoncode %{ class exceptionMetaclass(type): def __init__(self, name, bases, classdict): if Exception not in bases: bases.append(Exception) type.__init__(self, name, bases, classdict) %} class Xapian::Error { %pythoncode { __metaclass__ = exceptionMetaclass } }; -- Amaury Forgeot d'Arc |