__str__ vs __repr__

John Roth newsgroups at jhrothjr.com
Wed Jun 15 23:12:29 CEST 2005

"Jan Danielsson" <jan.danielsson at gmail.com> wrote in message 
news:42b021ba$1 at griseus.its.uu.se...
>  Sorry, but I Just Don't Get It. I did search the 'net, I did read the
> FAQ, but I'm too dumb to understand.
>   As far as I can gather, __str__ is just a representation of the
> object. For instance:
> class ServerConnection:
>   def __str__(self):
>      buf = "Server: " + self.name + "\n"
>      buf += "Sent bytes: " + str(self.sentBytes) + "\n"
>      buf += "Recv bytes: " + str(self.recvBytes) + "\n"
>      return buf
>   However, I don't understand what __repr__ should be. There's a phrase
> in the documentation which makes it highly confusing for a beginner like
> me: "If at all possible, this should look like a valid Python expression
> that could be used to recreate an object with the same value (given an
> appropriate environment).". What does that mean? Does it mean that I
> should return:
>   def __str__(self):
>      buf = "self.name=" + self.name + "\n"
>      buf += "self.sentBytes=" + str(self.sentBytes) + "\n"
>      buf += "self.recvBytes=" + str(self.recvBytes) + "\n"
>      return buf
>   ..or is there some other "valid Python expression" format which I
> have yet to encounter?

str() should be something that's meaningful to a human being when
it's printed or otherwise rendered. repr() should be something that
can round trip: that is, if you feed it into eval() it should reproduce
the object.

You can't always achieve either one, especially with very
complex objects, but that's the goal.

John Roth 

More information about the Python-list mailing list