Monday, September 5, 2011

__repr__ and unicode

__repr__ method returning Unicode string does not work in Python 2.5, 2.6 and 2.7 when called implicitly or via repr function.

class TestObject(object):
    def __repr__(self):
        return u'\u1234'
t = TestObject()
print (t.__repr__(), )
print (t, ) # same as print (repr(t), )

Running the above code produces

(u'\u1234',)
(Traceback (most recent call last):
  File "test_repr.py", line 6, in <module>
    print (t, )
UnicodeEncodeError: 'ascii' codec can't encode character u'\u1234' in position 0: ordinal not in range(128)

This bug has been filed in 2009, http://bugs.python.org/issue5876.

No comments:

Post a Comment