[Swig] Correct behavior for failure during __init__()

Jakob Schiotz schiotz1 at yahoo.com
Thu May 17 05:46:49 EDT 2001


--- Jeff Putsch <putsch at fiber.mxim.com> wrote:
> Howdy,
> 
> I'm wrapping a C library with with python and swig. I'm defining a
> class
> like this (wLib) is the wrapped C library:
> 
>    import wLib
> 
>    class ddId:
>        def __init__(self, arg1, arg2):
>            t1 = wLib.createObj(arg1, arg2)
>            if t1:
>                self.Id = t1
>            else:
>                NOW WHAT?
> 
> It is possible that the call to wLib.createObj does not succeed. In
> this
> case it is not clear to me what I should do where I've marked "NOW
> WHAT?"
> in the code above.

Raise an exception.  If I remember correctly, raising exceptions is the
only way to "abort" the construction of an object.  At least it is
(IMHO) the only reasonable thing to do, as exceptions are the standard
way to signal failure.

    class ddId:
        def __init__(self, arg1, arg2):
            t1 = wLib.createObj(arg1, arg2)
            if t1:
                self.Id = t1
            else:
                raise RuntimeError, "Failed to create wLib object."

You may want to define your own error.  If the only failure mode in the
library is a failing malloc, use a MemoryError instead.

Now your application can catch this exception and try to recover from
the error condition is there is something sensible to do when the
object creation failed.  Or just leave it uncaught, then your script
will abort.

I hope this helps,

Jakob


=====
Jakob Schiotz, CAMP and Department of Physics, Tech. Univ. of Denmark,
DK-2800 Lyngby, Denmark.  http://www.fysik.dtu.dk/~schiotz/
This email address is used for newsgroups and mailing lists
(spam protection).  Official email: schiotz @ fysik . dtu . dk
When spammed too much, I'll move on to schiotz2 at yahoo.com

____________________________________________________________
Do You Yahoo!?
Get your free @yahoo.co.uk address at http://mail.yahoo.co.uk
or your free @yahoo.ie address at http://mail.yahoo.ie




More information about the Python-list mailing list