[Python-Dev] args attribute of Exception objects

Sébastien de Menten sdementen at hotmail.com
Fri Apr 8 11:32:37 CEST 2005


When I need to make sense of a python exception, I often need to parse the 
string exception in order to retrieve the data.

    print foo
except NameError, e:
    print e.args
    symbol = e.args[0][17:-16]
==> ("NameError: name 'foo' is not defined", )


except NameError, e:
    print e.args
==> ("'int' object has no attribute 'foo'",)

Moreover, in the documentation about Exception, I read
"""Warning: Messages to exceptions are not part of the Python API. Their 
contents may change from one version of Python to the next without warning 
and should not be relied on by code which will run under multiple versions 
of the interpreter. """

So even args could not be relied upon !

Two questions:
  1) did I miss something in dealing with exceptions ?
  2) Could this be changed to .args more in line with:
    a) first example: e.args = ('foo', "NameError: name 'foo' is not 
    b) second example: e.args = (4, 'foo', "'int' object has no attribute 
  the message of the string can even be retrieved with str(e) so it is also 
  BTW, the Warning in the doc enables to change this :-) To be backward 
compatible, the error message could also be the first element of the tuple.


ps: There may be problems (that I am not aware) with an exception keeping 
references to other objects

More information about the Python-Dev mailing list