Altering the way exceptions print themselves

Peter Otten __peter__ at web.de
Sun Oct 22 15:03:46 EDT 2006


Irmen de Jong wrote:

> 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?

Nothing. That's just a chain of bad luck. As exceptions have become newstyle
classes __xxx__() special methods aren't looked up in the instance anymore.
 
> Or is there perhaps a different way to do what I want?

Does it suffice to set the excepthook? If so, you might want something less
hackish than

class wrap_exc(object):
    def __init__(self, exception):
        self.__exception = exception
    def __getattr__(self, name):
        return getattr(self.__exception, name)
    def __str__(self):
        return "yadda"

def eh(etype, exception, tb):
    eh_orig(etype, wrap_exc(exception), tb)

eh_orig = sys.excepthook

Peter



More information about the Python-list mailing list