How to make __repr__ to return unicode string

xralf picture xralf · Feb 16, 2012 · Viewed 11k times · Source

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

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Feb 16, 2012

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