The __str__ method

__str__(self)

Called by the str built-in function and by the print statement to compute the informal string representation of an object. This differs from __repr__ in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

 

Comment:

"The return value must be a string object." Does this mean it can be a *Unicode* string object? This distinction is ambiguous to me because unicode objects and string objects are both subclasses of basestring. May a __str__() return a Unicode object?

Posted by Adrian Holovaty (2006-12-05)

From what I can tell, you can return a Unicode string from __str__, but str() will attempt to convert it to an 8-bit string using the default encoding, and raise an error if that's not possible. A direct method call works fine, though... I've forwarded your question to python-dev. /F

Update: You can use unicode() instead of str() to get the Unicode string you've returned from __str__. At least under 2.5; no time to test on older versions right now. /F

A Django site. rendered by a django application. hosted by webfaction.