FAQ: __str__ vs __repr__

Sébastien Boisgérault Sebastien.Boisgerault at gmail.com
Wed Jun 15 09:06:14 EDT 2005


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




More information about the Python-list mailing list