Weird exception in my, um, exception class constructor

Arnaud Delobelle arnodel at googlemail.com
Tue May 27 16:34:53 EDT 2008


"Joel Koltner" <zapwireDASHgroups at yahoo.com> writes:

> I have a generic (do nothing) exception class that's coded like this:
>
> class MyError(exceptions.Exception):
>     def __init__(self,args=None):
>         self.args = args
>
> When I attempt to raise this exception via 'raise MyError' I get an
> exception within the MyError constructor __init__ as follows:
>
> Traceback (most recent call last):
> [lines deleted]
>   File "c:\Documents and Settings\Joel.Kolstad\My Documents\Python\
> MyStuff.py", line 7, in __init__
>     self.args = args
> TypeError: 'NoneType' object is not iterable

That's because the class 'Exception' defines a descriptor 'args' which
has to be a sequence.  Just call 'args' something else, and it will
work.  E.g.

>>> class MyError(Exception):
...     def __init__(self, args=None):
...         self.myargs = args
... 
>>> MyError()
MyError()


OTOH you could just take advantage of Exception.args:

>>> class MyError(Exception): pass
... 
>>> MyError()
MyError()
>>> MyError(1, 2, 3)
MyError(1, 2, 3)

(Details in the documentation are a bit scant, but see
http://docs.python.org/lib/module-exceptions.html)

HTH

-- 
Arnaud



More information about the Python-list mailing list