Correct behavior for failure during __init__()

Aahz Maruch aahz at panix.com
Wed May 16 19:28:22 EDT 2001


In article <mailman.990053304.18687.python-list at python.org>,
Jeff Putsch  <putsch at fiber.mxim.com> wrote:
>
>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.

Generally, the answer is to raise an exception (presuming this situation
means that an error has occurred that makes the new instance unusable).
For example, the open() function returns a file object; if open() fails,
it raises an exception (usually an IOError):

>>> open('foo')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'foo'
-- 
                      --- Aahz  <*>  (Copyright 2001 by aahz at pobox.com)

Androgynous poly kinky vanilla queer het Pythonista   http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

"It's such a fine line between stupid and clever."  --David St. Hubbins



More information about the Python-list mailing list