Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make __repr__ to return unicode string

I call a __repr__() function on object x as follows:

val = x.__repr__()

and then I want to store val string to SQLite database. The problem is that val should be unicode.

I tried this with no success:

val = x.__repr__().encode("utf-8")

and

val = unicode(x.__repr__())

Do you know how to correct this?

I'm using Python 2.7.2

like image 946
xralf Avatar asked Feb 16 '12 20:02

xralf


2 Answers

The representation of an object should not be Unicode. Define the __unicode__ method and pass the object to unicode().

like image 174
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 16:09

Ignacio Vazquez-Abrams


repr(x).decode("utf-8") and unicode(repr(x), "utf-8") should work.

like image 22
Roman Bodnarchuk Avatar answered Sep 30 '22 18:09

Roman Bodnarchuk