[Python-Dev] unicode and __str__

"Martin v. Löwis" martin at v.loewis.de
Mon Aug 30 22:57:36 CEST 2004


Neil Schemenauer wrote:
> Also, I'm a little unclear on the purpose of the __unicode__ method.
> If you can return unicode from __str__ then why would I want to
> provide a __unicode__ method?  Perhaps it is meant for objects that
> can either return a unicode or a string representation depending on
> what the caller prefers.  I have a hard time imagining a use for
> that.

It's what unicode() returns:

 >>> class A:
...   def __str__(self):return "1"
...   def __unicode__(self): return u"2"
...
 >>> a=A()
 >>> str(a)
'1'
 >>> unicode(a)
u'2'

str() is guaranteed to return a byte string; unicode() is guaranteed
to return a unicode string.

Regards,
Martin


More information about the Python-Dev mailing list