Roy Smith <r...@panix.com> writes: > In article <5334b747$0$29994$c3e8da3$54964...@news.astraweb.com>, > Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > > > On Thu, 27 Mar 2014 08:52:24 -0400, Roy Smith wrote: > > > Give ma a real-life situation where you would want such behavior > > > [the ‘datetime.timedelta.__str__’ method returning a string > > > showing some portions negative and others positive]. > > > > Easy -- I'm debugging timedelta routines, and I want to easily see > > that the timedeltas calculated match what I expect them to be when I > > print them. The quickest, easiest and simplest way is for > > str(timedelta) to follow the internal representation. > > That's what __repr__() is for.
Indeed, that is why Python's data model defines separate ‘__str__’ and ‘__repr__’ methods. object.__repr__(self) […] 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). If this is not possible, a string of the form <...some useful description...> should be returned. <URL:http://docs.python.org/3/reference/datamodel.html#object.__repr__> object.__str__(self) […] compute the “informal” or nicely printable string representation of an object. […] a more convenient or concise representation can be used. <URL:http://docs.python.org/3/reference/datamodel.html#object.__str__> If you're a programmer wanting to know about the internal representation of an object, call its ‘__repr__’ method (by calling ‘repr(foo)’). If you're wanting to see a string representation that follows the *semantics* of the object, call its ‘__str__’ method (by calling ‘str(foo)’). If the ‘__str__’ method follows the internal representation at the expense of the user's conceptual model, that's terrible (which I think is what Roy means by “braindead”). I wouldn't go as far as that insult, because it could be mere omission: The default implementation [of ‘__str__’] defined by the built-in type object calls object.__repr__(). So, where ‘str(foo)’ is returning an unhelpful representation that follows the implementation, it could simply be that there is no ‘__str__’ defined for that type. > > Oh look, that's exactly what the docs say: > > > > "String representations of timedelta objects are normalized > > similarly to their internal representation. This leads to somewhat > > unusual results for negative timedeltas." > > Yes, I know that's what the docs say. That's why it's not an > implementation bug. It's a design bug :-) One which to some extent violates the defined data model for Python objects, and hence should be fixed. -- \ “I don't know half of you half as well as I should like, and I | `\ like less than half of you half as well as you deserve.” —Bilbo | _o__) Baggins | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list