FAQ: __str__ vs __repr__
Peter Hansen
peter at engcorp.com
Wed Jun 15 11:39:11 EDT 2005
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
More information about the Python-list
mailing list