Unicode Objects in Tuples

Roy Smith roy at panix.com
Sat Oct 12 09:11:00 EDT 2013


In article <mailman.1034.1381575143.18130.python-list at python.org>,
 Ned Batchelder <ned at nedbatchelder.com> wrote:

> This idea that the repr can reconstruct the object always fell flat with 
> me since the vast majority of classes don't have a repr that works that 
> way.  I look at it a little differently: the repr is meant to be as 
> unambiguous as possible to a developer.  It turns out that Python 
> literal syntax is really good at that, so where possible, that's what's 
> used.   But most classes don't make an attempt to create a Python 
> expression, because that's very difficult

Well, it's not actually difficult.  You could imagine doing something 
like:

def __repr__(self):
    return "pickle.loads(%s)" % pickle.dumps(self)

and while you can paste that into a REPL, it's not really useful to most 
people.

What we do with our database model layer is have the repr include the 
name of the class and the primary key.  So:

>>> str(u)
'roysmith'
>>> repr(u)
"<User 1000564: u'roysmith'>"

That follow's Ned's idea that reprs should be unambiguous.  In this 
case, if I want to reconstitute myself as an object, I can just do a 
database query for user_id = 1000564.



More information about the Python-list mailing list