Exception.__init__ needed in derived class?

Steven Taschuk staschuk at telusplanet.net
Fri Apr 25 10:40:56 EDT 2003


Quoth george young:
> [python-2.3a1]
> Does class Exception have a constructor __init__ that needs
> to be called?  I couldn't find this in the docs.  I see many
> uses of inheriting from Exception without invoking
> Exception.__init__(self), but nobody ever *said* that this 
> was safe to leave out...
> 
> Pychecker complains about this, which is what brought it to
> mind.  I can certainly invoke it just to make pychecker 
> happy, but I wondered...

Exception does have an __init__, and probably it should be called.
If you don't call it, e.args will not be initialized:

    >>> e = Exception(1, 2, 3)
    >>> e.args
    (1, 2, 3)
    >>> class MyException(Exception):
    ...     def __init__(self, a, b, c):
    ...         self.a = a
    ...         self.b = b
    ...         self.c = c
    ... 
    >>> e = MyException(1, 2, 3)
    >>> e.args
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: MyException instance has no attribute 'args'

This might or might not be important to you.  Afaik the only place
.args is used is in Exception.__str__; if you're overriding
__str__ as well, that won't matter.  But other code might have a
use for .args; debuggers, for example.  In general it's good form
to call __init__ to ensure that the base class's invariants are
preserved -- unless you have a good reason for breaking them.

Many subclasses of Exception are just
    class HullBreachError(Exception):
        pass
and so they inherit Exception.__init__ along with everything else.

(Another, somewhat silly, way to get named attributes:
    class HullBreachError(Exception):
        a = property(lambda self: self.args[0])
        b = property(lambda self: self.args[1])
        c = property(lambda self: self.args[2])
This is inferior.  For one thing, it would be better to have the
meanings of the __init__ arguments documented in __init__'s
docstring.)

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list