The convention is that you use repr
to get a string that represents the object, and str
to describe it. repr
is used more for debugging, str
for regular printing. The idea is that the output of repr is something that looks like code you could eval, and often it is. However, you can't rely on that. If you have to convert an object to a string and back, use pickle
or json
.
For example:
>>> greeting = "Hello"
>>> print str(greeting)
Hello
>>> print repr(greeting)
'Hello'
If you are writing your own class, and it is very simple, you can make __repr__
return something that can be eval'd:
class Song(object):
def __init__(self, title, artist):
self.title = title
self.artist = artist
def __repr__(self):
return "Song(%r, %r)" % (self.title, self.artist)
def __str__(self):
return "%s - %s" % (self.artist, self.title)
Note how I use %r
to get the repr
of the title and artist. This takes care of escaping and quoting (for python) automatically, and allows me to eval the result of repr(a_song)
, although I wouldn't do that outside of debugging. Again, str
returns something you would print to the user, repr
something that helps you debugging. If the class gets more complicated than this, you won't be able to return something complete or evalable from repr
. The convention here is to return a concise string to identify you instance, usually with angular brackets:
>>> repr(type(None))
"<type 'NoneType'>"
>>> import gtk
>>> win = gtk.Window()
>>> repr(win)
'<gtk.Window object at 0x10de45690 (GtkWindow at 0x7fdd89240000)>'