Is this the right way to use unicode in a user defined Exception?

Terry Reedy tjreedy at udel.edu
Thu Feb 26 09:12:02 CET 2009


一首诗 wrote:
> #------------------------------------------------
> class MyError(Exception):
>     def __init__(self):
>         self.message = u'Some Chinese:中文'
> 
>     def __str__(self):
>         return self.message.encode('utf8')
> #------------------------------------------------
> 
> This is an exception that I defined.   I have to pass it to third
> party libraries.
> 
> As many libraries simply use str(e) to log, if I don't encode it in
> __str___, they will fail.
> 
> But I am not quite certain if it's the right thing to do.   Shouldn't
> every library expect to use unicode everywhere?
> 
> Shouldn't they use something like :
> 
> log(unicode(e))

In 3.0, text is unicode.  So libraries will mostly expect it.




More information about the Python-list mailing list