confused about __str__ vs. __repr__

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Dec 18 20:02:07 EST 2008


On Thu, 18 Dec 2008 10:49:27 -0500, Neal Becker wrote:

> So if I want to overload something in my custom class, so that I get a
> nice string whether it's printed directly, or as part of a container,
> what is the recommendation?  Overload both __str__ and __repr__?

Either or both or neither, whatever you feel is best. Or create a pretty-
print method, and call that manually. I've done all of the above at times.

Remember though, that ideally you should be able to round-trip your 
objects to strings and back again:

obj = MyClass(args)
eval(repr(obj)) == obj

should be true.

This isn't compulsory, and it isn't always possible, but unless you have 
good reason to avoid it, you should aim for that behaviour.


BTW Neal, your posts aren't word wrapped. When I read your posts, I get 
each paragraph as one extremely LONG line scrolling way out to the side. 
That's against the Internet standards for both email and Usenet, so could 
you please configure your client to word-wrap at (say) 70 characters?



-- 
Steven



More information about the Python-list mailing list