Simple unicode-safe version of str(exception)?

Donn Cave donn at u.washington.edu
Tue Apr 29 01:46:05 CEST 2008


In article <481650E3.4060603 at v.loewis.de>,
 "Martin v. Löwis" <martin at v.loewis.de> wrote:

> >> I have code like this:
> >> except Exception, e:
> >>    self.setState(self.Failed, str(e))
> >> which fails if the exception contains a unicode argument.
> > 
> > Fails how?
> 
> ASCII encoding error, I suppose. It fails only if a) one argument
> is a Unicode object, and b) that Unicode object contains non-ASCII
> parameters.

Seem ironic that this fails even though pretty nearly anything
else is a valid input to str() -- socket, dict, whatever?

A sort of generic solution might be to follow str's behavior
with respect to '__str__', extending it to fall back to repr()
whatever goes wrong.


    def xtr(a):
        try:
            return str(a)
        except:
            return repr(a)

    ...
        self.setState(self.Failed, xtr(e))

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list