FAQ: __str__ vs __repr__

Discussion in 'Python' started by Jan Danielsson, Jun 15, 2005.

  1. 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?
     
    Jan Danielsson, Jun 15, 2005
    #1
    1. Advertising

  2. Jan Danielsson a écrit :
    > 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.


    .... yep, and this representation is built for human eyes. Don't
    worry too much if it does not display every bit of information
    contained in your object. Pretty printing rules ...

    >>> str(0.1)

    0.1
    >>> str("it's a bad idea")

    "it's a bad idea"

    > However, I don't understand what __repr__ should be.


    It is an *exact* (if possible) description of the object's content,
    nicely packaged into a string.

    >>> repr(0.1)

    0.10000000000000001
    >>> repr("it's a bad idea")

    '"it\'s a bad idea"'


    > 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).".


    It means that the equality eval(repr(x)) == x should hold.

    Cheers,

    SB
     
    =?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=, Jun 15, 2005
    #2
    1. Advertising

  3. Errata:

    >>> str(0.1)

    '0.1'
    >>> str("it's a bad idea")

    "it's a bad idea"

    >>> repr(0.1)

    ' 0.10000000000000001'
    >>> repr("it's a bad idea")

    '"it\'s a bad idea"'


    SB
     
    =?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=, Jun 15, 2005
    #3
  4. Well, It means that eval(repr(x)) == x if at all possible.
    Basically:
    repr('abc') -> 'abc'
    str('abc') -> abc

    You'll notice that 'abc' is a valid python expression for the string,
    while abc is not a valid string expression.

    Andreas

    On Wed, Jun 15, 2005 at 02:46:04PM +0200, Jan Danielsson wrote:
    > 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?
    > --
    > http://mail.python.org/mailman/listinfo/python-list
     
    Andreas Kostyrka, Jun 15, 2005
    #4
  5. Jan Danielsson

    Greg Krohn Guest

    Basically __repr__ should return a string representaion of the object,
    and __str__ should return a user-friendly pretty string. So maybe:

    class Person:
    ...
    def __repr__(self):
    return '<Person: %s, %d, %s>' % (self.name, self.age, self.sign)

    def __str__(self):
    return self.name

    See this for a better explanation:

    http://www.faqts.com/knowledge_base/view.phtml/aid/1331/fid/241
     
    Greg Krohn, Jun 15, 2005
    #5
  6. Jan Danielsson

    Peter Hansen Guest

    Jan Danielsson wrote:
    > 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. [snip]


    > However, I don't understand what __repr__ should be.


    __repr__ shouldn't be anything, if you don't have an actual need for it.
    Neither should __str__.

    But if you have a need for something, and you're not sure which to use,
    think of it this way. If you are trying to output a representation of
    the object for use in debugging, such as in a debug log file, then use
    __repr__ and make it look like whatever you want, but preferably
    following the <Angle brackets convention> like all the builtin stuff.

    If you have a need for some representation of the data to use in your
    application for non-debugging purposes, such as perhaps to display data
    to a user, or to write data to an output file, then __str__ is a good
    candidate, and you can make it look like whatever you need.

    Just don't waste your time defining either a __repr__ or a __str__ just
    because those methods exist. That won't do anyone any good.

    -Peter
     
    Peter Hansen, Jun 15, 2005
    #6
  7. Jan Danielsson

    Donn Cave Guest

    In article <42b021ba$>,
    Jan Danielsson <> wrote:

    > 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.


    No, it is not. It is a conversion to string. The result has
    no trace of the original object, per se -- in principle, many
    different kinds of object could yield the same result. Suppose
    str(x) -> "42". Is x an int? a string? an XMLParseResult?
    AnswerToLifeTheUniverseAndEverything? You don't want to know,
    that's why you use str().

    The "friendly" idea is vacuous if you look hard enough at it,
    and won't really help.

    > 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?


    It's kind of a bad idea that the Python world isn't ready to
    let go of yet.

    repr() is really the representation of the object. If you
    look at the result of repr(x), you should indeed see some
    clue to the original object. I guess this is what gives
    people the idea that str() is friendly, because as a rule
    users are not interested in the original object -- but
    there are exceptions, for example you may find the quotes
    useful around a string, depending on the situation. The
    object information also leads to the marshalling idea, but
    of course this isn't (and can't be) implemented for many
    objects so we can't expect this to work reliably with
    random objects. The price we pay for the notion is mostly
    in the "fix" for float repr, which now displays the float
    in all its imprecise glory and routinely confounds people
    who don't understand what that's about.

    Donn Cave,
     
    Donn Cave, Jun 15, 2005
    #7
  8. On Wednesday 15 June 2005 08:06 am, Sébastien Boisgérault wrote:
    > Jan Danielsson a écrit :
    > > However, I don't understand what __repr__ should be.

    > It is an *exact* (if possible) description of the object's content,
    > nicely packaged into a string.


    However, this is often not the case. Frequently __repr__ will
    return something like this:

    >>> import re
    >>> r = re.compile('\w+\d*')
    >>> r

    <_sre.SRE_Pattern object at 0x401a89b0>
    >>> str(r)

    '<_sre.SRE_Pattern object at 0x401a89b0>'
    >>> repr(r)

    '<_sre.SRE_Pattern object at 0x401a89b0>'

    So don't obsess over it. For many objects it isn't worth
    the trouble, and for others, str() and repr() are sensibly the
    same thing, but for some, the distinction is useful. That's
    all.

    --
    Terry Hancock ( hancock at anansispaceworks.com )
    Anansi Spaceworks http://www.anansispaceworks.com
     
    Terry Hancock, Jun 15, 2005
    #8
  9. Jan Danielsson wrote:
    > 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.


    Say we define a string "s" as follows:

    >>> s = 'hello'


    If we print "s", we see its string form (__str__):

    >>> print s

    hello

    However, if we just examine "s", we see its representation (__repr__):

    >>> s

    'hello'

    This can be verified by calling str() and repr() on the string:

    >>> str(s)

    'hello'
    >>> repr(s)

    "'hello'"

    So, the result of repr() includes quotes, whereas the result of str()
    does not. This has useful properties when the object is part of a more
    complex structure. For instance, these two expressions print out the same:

    >>> [s, s]

    ['hello', 'hello']
    >>> print [s, s]

    ['hello', 'hello']

    That's because, in either case, the repr() form is used. If Python only
    had str(), we would probably expect str(s) = s, so we'd instead see
    something like this imaginary snippet:

    >>> [s, s]

    [hello, hello]
    >>> repr([s, s])

    '[hello, hello]'

    So, the convention in Python is that repr() returns a string that, when
    evaluated, returns the original object. This is not always easy or
    possible to do, but if you can do it, your objects will print nicely
    when nested within Python's built-in data structures. Python's actual
    behavior is this:

    >>> repr([s, s])

    "['hello', 'hello']"

    And therefore:

    >>> eval(repr([s, s]))

    ['hello', 'hello']

    Also worth noting is that if you define __repr__, the default behavior
    of __str__ is to delegate to that definition, so if you only want to
    define one, it's often more convenient to just define __repr__.

    Dave
     
    Dave Benjamin, Jun 15, 2005
    #9
  10. Jan Danielsson

    John Roth Guest

    Re: __str__ vs __repr__

    "Jan Danielsson" <> wrote in message
    news:42b021ba$...
    > 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
     
    John Roth, Jun 15, 2005
    #10
  11. Jan Danielsson

    Donn Cave Guest

    Re: __str__ vs __repr__

    Quoth "John Roth" <>:
    ....
    | str() should be something that's meaningful to a human being when
    | it's printed or otherwise rendered.

    I can't believe how many people cite this explanation - meaningful,
    friendly, pretty to a human being. What on earth does this mean,
    that couldn't be said more unambiguously?

    According to my impression of common applications for Python programs,
    rarely would anyone be looking at the output for esthetic gratification.
    I mean, imagine your users casting an appraising eye over the contours
    of a phrase emitted by the program, and praising the rhythmic effect of
    the punctuation it chose to use, or negative space created by tabs. heh.

    Whether for human eyes or any destination, properly formed output will
    carry the information that is required for the application, in a complete
    and unambiguous way and in the format that is most readily processed,
    and it will omit extraneous information. Are we saying anything other
    than this?

    Donn Cave,
     
    Donn Cave, Jun 16, 2005
    #11
  12. Jan Danielsson

    John Roth Guest

    Re: __str__ vs __repr__

    "Donn Cave" <> wrote in message
    news:1118898421.887013@yasure...
    > Quoth "John Roth" <>:
    > ...
    > | str() should be something that's meaningful to a human being when
    > | it's printed or otherwise rendered.
    >
    > I can't believe how many people cite this explanation - meaningful,
    > friendly, pretty to a human being. What on earth does this mean,
    > that couldn't be said more unambiguously?
    >
    > According to my impression of common applications for Python programs,
    > rarely would anyone be looking at the output for esthetic gratification.
    > I mean, imagine your users casting an appraising eye over the contours
    > of a phrase emitted by the program, and praising the rhythmic effect of
    > the punctuation it chose to use, or negative space created by tabs. heh.
    >
    > Whether for human eyes or any destination, properly formed output will
    > carry the information that is required for the application, in a complete
    > and unambiguous way and in the format that is most readily processed,
    > and it will omit extraneous information. Are we saying anything other
    > than this?


    I thought that's what I said. I fail to see how you derive any other
    meaning from it. Possibly less verbiage and a concerete example
    of how "meaningful" equates to "esthetics that obfustificate understanding"
    and does not equate to "immediately useable, without having to wade
    through a lot of irrelvant mental transformations" would help my
    understanding.

    John Roth
    >
    > Donn Cave,
     
    John Roth, Jun 16, 2005
    #12
  13. Jan Danielsson

    Donn Cave Guest

    Re: __str__ vs __repr__

    In article <>,
    "John Roth" <> wrote:

    > "Donn Cave" <> wrote in message
    > news:1118898421.887013@yasure...
    > > Quoth "John Roth" <>:
    > > ...
    > > | str() should be something that's meaningful to a human being when
    > > | it's printed or otherwise rendered.
    > >
    > > I can't believe how many people cite this explanation - meaningful,
    > > friendly, pretty to a human being. What on earth does this mean,
    > > that couldn't be said more unambiguously?
    > >
    > > According to my impression of common applications for Python programs,
    > > rarely would anyone be looking at the output for esthetic gratification.
    > > I mean, imagine your users casting an appraising eye over the contours
    > > of a phrase emitted by the program, and praising the rhythmic effect of
    > > the punctuation it chose to use, or negative space created by tabs. heh.
    > >
    > > Whether for human eyes or any destination, properly formed output will
    > > carry the information that is required for the application, in a complete
    > > and unambiguous way and in the format that is most readily processed,
    > > and it will omit extraneous information. Are we saying anything other
    > > than this?

    >
    > I thought that's what I said. I fail to see how you derive any other
    > meaning from it. Possibly less verbiage and a concerete example
    > of how "meaningful" equates to "esthetics that obfustificate understanding"
    > and does not equate to "immediately useable, without having to wade
    > through a lot of irrelvant mental transformations" would help my
    > understanding.


    Not sure if that's a question. Maybe I can state this more clearly.

    Observation: Most who responded to this question offered an
    explanation of __str__ like "friendly to a human being",
    using one or more of meaningful, friendly or pretty. The
    online manual uses "informal".

    1. These words are woefully ambiguous, to be applied in computer
    programming. While there may be some kind of absolute basis
    for esthetic appreciation, that clearly doesn't apply here,
    and terms like this have to be strictly relative to context
    created by the application.
    Summary: By itself, friendly to a human being is a vacuous
    notion and doesn't help anyone.

    2. If we attempt to support the explanation with a more rigorous
    examination of the principles and how they'd apply to a string
    conversion, it's hard to make this come out favoring str over
    repr. In the end, they should both be meaningful and friendly,
    by any uncontorted definition of those terms.
    Summary: To the extent that they have any meaning, they are
    probably applied incorrectly as an explanation of __str__.

    So, among other conclusions, the documentation should be changed
    to offer a more sensible explanation of __str__.

    Donn Cave,
     
    Donn Cave, Jun 16, 2005
    #13
  14. On 6/15/05, Peter Hansen <> wrote:
    > __repr__ shouldn't be anything, if you don't have an actual need for it.
    > Neither should __str__.


    Oh, I don't know. __str__ is so frequently useful in debugging and
    logging that I always try and do something useful with it.

    --
    Cheers,
    Simon B,
    ,
    http://www.brunningonline.net/simon/blog/
     
    Simon Brunning, Jun 21, 2005
    #14
  15. Jan Danielsson

    Peter Hansen Guest

    Simon Brunning wrote:
    > On 6/15/05, Peter Hansen <> wrote:
    >>__repr__ shouldn't be anything, if you don't have an actual need for it.
    >> Neither should __str__.

    >
    > Oh, I don't know. __str__ is so frequently useful in debugging and
    > logging that I always try and do something useful with it.


    Interesting: for the same purpose, I would define __repr__.

    But I still define it only when I actually care about the details, since
    otherwise the default __repr__ is always there. Spending time figuring
    out a potentially more useful __str__/__repr__ (how nice that we've
    confused the issue of which to use, again! ;-) ) is not my idea of a
    good use of time, what with YAGNI and all from XP...

    -Peter
     
    Peter Hansen, Jun 21, 2005
    #15

  16. >> __repr__ shouldn't be anything, if you don't have an actual need for
    >> it. Neither should __str__.


    Simon> Oh, I don't know. __str__ is so frequently useful in debugging
    Simon> and logging that I always try and do something useful with it.

    And sometimes __repr__ inherited from a base class doesn't tell you much.
    If you inherit from gobject (the basic object in PyGtk), the repr is
    something like

    <Future object (__main__+Base) at 0x851384c>

    That is, it identifies the class name, its inheritance hierarchy (Future ->
    Base -> __main__ in this case) and its memory address. That's perhaps
    useful by itself in some contexts, and I can understand that the PyGtk folks
    couldn't really stuff more specific info in there, but it does nothing to
    distinguish one instance's state from that of another.

    Skip
     
    Skip Montanaro, Jun 21, 2005
    #16
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jim Newton

    how to use __str__ and __repr__?

    Jim Newton, Jun 7, 2004, in forum: Python
    Replies:
    15
    Views:
    566
    Peter Maas
    Jun 9, 2004
  2. Dan Sommers
    Replies:
    3
    Views:
    313
    Serge Orlov
    Feb 19, 2005
  3. Neal Becker

    confused about __str__ vs. __repr__

    Neal Becker, Dec 18, 2008, in forum: Python
    Replies:
    1
    Views:
    261
    Diez B. Roggisch
    Dec 18, 2008
  4. Neal Becker

    Re: confused about __str__ vs. __repr__

    Neal Becker, Dec 18, 2008, in forum: Python
    Replies:
    3
    Views:
    359
    Steve Holden
    Dec 18, 2008
  5. Neal Becker

    Re: confused about __str__ vs. __repr__

    Neal Becker, Dec 18, 2008, in forum: Python
    Replies:
    12
    Views:
    630
    Carl Banks
    Dec 19, 2008
Loading...

Share This Page