Use __repr__ to show the programmer's representation (was: Need help understanding list structure)

Dan Strohl D.Strohl at F5.com
Tue May 3 14:35:48 EDT 2016


> > One other point for you, if your "__repr__(self)" code is the same as
> > the "__str__(self)" code (which it looks like it is, at a glance at
> > least), you can instead reference the __str__ method and save having a
> > duplicate code block...
> 
> Alternatively, consider: the ‘__repr__’ method is intended to return a
> *programmer's* representation of the object. Commonly, this is text which
> looks like the Python expression which would create an equal
> instance::

Definitely true per what _repr__ is supposed to do per python docs.   However, in this case, that might not have solved the problem if the goal was to return the same as a __str__.  (Though to be fair, I don’t really know what the actual problem was, so I might provide a different approach with a different goal <grin>).

I also have never actually used repr() to create code that could be fed back to the interpreter (not saying it isn’t done, just that I haven’t run into needing it), and there are so many of the libraries that do not return a usable repr string that I would hesitate to even try it outside of a very narrow use case.

Personally, I normally use __repr__ to give me a useful troubleshooting representation of the object... but that representation might not be exactly the same as what would recreate the object since I might show information that is dynamic to the current state (like, the name of the parent instead of just a pointer or something).

I know that isn’t per the rules, but in the end, it makes it easier for me to troubleshoot the code.

Having said that, Ben is totally correct in terms of the "right" way to do it, my earlier suggestion was not "right".

Dan



More information about the Python-list mailing list