It seems to me that built-in functions __repr__
and __str__
have an important difference in their base definition.
>>> t2 = u'\u0131\u015f\u0131k'
>>> print t2
ışık
>>> t2
Out[0]: u'\u0131\u015f\u0131k'
t2.decode
raises an error since t2
is a unicode string.
>>> enc = 'utf-8'
>>> t2.decode(enc)
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
__str__
raises an error as if decode()
function is being called:
>>> t2.__str__()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
but __repr__
works without problem:
>>> t2.__repr__()
Out[0]: "u'\\u0131\\u015f\\u0131k'"
Why does __str__
produce an error whereas __repr__
work properly?
This small difference seems to cause a bug in one django application that I am working on.