Simple unicode-safe version of str(exception)?

Russell E. Owen rowen at cesmail.net
Tue Apr 29 21:54:04 CEST 2008


In article <87zlrcmxuk.fsf at physik.rwth-aachen.de>,
 Torsten Bronger <bronger at physik.rwth-aachen.de> wrote:

> Hallöchen!
> 
> Russell E. Owen writes:
> 
> > [...]
> >
> > So...to repeat the original question, is there any simpler
> > unicode-safe replacement for str(exception)?
> 
> Please show us the tracebacks you get becuae unicode(s) must fail,
> too, if there are non-ASCII characters involved.

Why?

What I am trying to do is get a unicode representation of the arguments 
of an exception. str(e), the obvious solution, fails if the exception 
contains one argument that is a unicode string that cannot be decoded to 
ASCII:

UnicodeEncodeError: 'ascii' codec can't encode character...ordinal not 
in range(128)

What I do with the resulting unicode string afterwards is a different 
issue. (As a matter of fact I display it on a widget that can display 
unicode, but if I tried to print it to my Mac Terminal it would complain 
about the non-ASCII characters--something I should look into fixing 
someday).

But in any case, here are the exceptions you wanted to see. This is 
using Python 2.5.2 on a Mac:

>>> d =u"\N{DEGREE SIGN}"
>>> d
u'\xb0'
>>> str(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in 
position 0: ordinal not in range(128)
>>> e = Exception(d)
>>> str(e)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in 
position 0: ordinal not in range(128)
>>> e
Exception(u'\xb0',)
>>> ",".join([unicode(s) for s in e.args])
u'\xb0'
>>> 

Based on the dearth of better replacements I've gone with the solution 
that is shown as the last line above, coded as the following function 
(incorporating Donn Cave's excellent suggestion to use repr as a 
fallback). It has the minor issue that it can mask KeyboardInterrupt on 
older versions of Python but it's close enough. A lot of work to replace 
str(exc).

def strFromException(exc):
    """Unicode-safe replacement for str(exception)"""
    try:
        return str(exc)
    except Exception:
        try:
            return ",".join([unicode(s) for s in exc.args])
        except Exception:
            # in case exc is some unexpected type
            return repr(exc)

-- Russell



More information about the Python-list mailing list