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

Chris Angelico rosuav at gmail.com
Tue May 3 19:40:24 EDT 2016


On Wed, May 4, 2016 at 4:35 AM, Dan Strohl via Python-list
<python-list at python.org> wrote:
> 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.

Here's a repr that I like using with SQLAlchemy:

def __repr__(self):
    return (self.__class__.__name__ + "(" +
        ", ".join("%s=%r" % (col.name, getattr(self, col.name)) for
col in self.__table__.columns) +
    ")")

That results in something that *looks* like you could eval it, but you
shouldn't ever actually do that (because it'd create a new object).
It's still an effective way to make the repr readable; imagine a list
that prints out like this:

[Person(id=3, name="Fred"), Person(id=6, name="Barney"), Person(id=8,
name="Joe")]

You can tell exactly where one starts and another ends; you can read
what's going on with these record objects. Making them
"pseudo-evalable" is worth doing, even if you should never *actually*
eval them.

ChrisA



More information about the Python-list mailing list