Altering the way exceptions print themselves

Irmen de Jong irmen.NOSPAM at xs4all.nl
Sun Oct 22 19:50:22 CEST 2006


Hello,

I want to alter the way exceptions print themselves.
More specifically, I'd like to extend the __str__ method of
the exception's class so that it is printed in a different way.

I used to replace the __str__ method on the exception object's
class by a custom method, but that breaks my code on Python 2.5
because of the following error I'm getting:

TypeError: can't set attributes of built-in/extension type 'exceptions.TypeError'

Well, ok. So I tried to improve my code and not alter the class,
but only the exception object. I came up with this:



def __excStr__(self):
     return "[[[EXCEPTION! "+self.originalStr()+"]]"


... some code that raises an exception 'ex' ....

import new
newStr = new.instancemethod( __excStr__, ex, ex.__class__)
ex.__str__=newStr


On Python 2.4 the above code works as I expect, however on Python 2.5
it doesn't seem to have any effect... What am I doing wrong?

Or is there perhaps a different way to do what I want?


Thanks!
--Irmen de Jong





More information about the Python-list mailing list