Simple unicode-safe version of str(exception)?

Russell E. Owen rowen at cesmail.net
Tue Apr 29 12:16:21 EDT 2008


In article <donn-FE27D0.16460528042008 at gnus01.u.washington.edu>,
 Donn Cave <donn at u.washington.edu> wrote:

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

I agree. In fact str(a) works if a is a dict or list that contains 
unicode data! Pity the same is not true of exceptions.

Should I report this as a bug? I suspect it's a misfeature.

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

Yes. That is a more flexible alternative to what I've adopted:
    def exStr(ex):
        return ",".join([unicode(s) for s in f.args])
the latter gives better output for the case I'm interested in, but only 
handles exceptions.

Oh well. I'll stick to my solution and hope that Python 2.6 and 3.0 fix 
the problem in a more sensible fashion.

-- Russell



More information about the Python-list mailing list