__unicode__ method for exception object

Manlio Perillo manlio_perilloNO at SPAMlibero.it
Sun Jul 8 22:34:50 CEST 2007


Il Sun, 08 Jul 2007 10:02:01 +1000, Ben Finney ha scritto:

> Manlio Perillo <manlio_perilloNO at SPAMlibero.it> writes:
> 
>> I have just noticed that exception objects does not handle well Unicode
>> arguments.
> 
> This error is unrelated to the fact that you created an exception
> object.
> 

No, it is related.

>> >>> e = RuntimeError(u'àèìòù')
>> >>> str(e)
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 
> Your terminal has been detected as using the 'ascii' encoding, so while
> that's true no attempt to output non-ASCII characters will work.
> 
> You'll need to change whatever settings are on your terminal emulator so
> that it is using an encoding (such as 'utf-8') which can display the
> characters you want.


This is not a problem with the terminal.
And the problem is not with str(e) but with unicode(e).

unicode(e) converts the exception argument to an Unicode object, but 
since no __unicode__ object is defined, it firsts calls the __str__ 
method (and this, of course, fails, since the default encoding in CPython 
is us-ascii) and then converts the result to an Unicode object using, 
again, the default encoding.



Regards  Manlio Perillo



More information about the Python-list mailing list