__str__ vs. __repr__

Gordon McMillan gmcm at hypernet.com
Fri Nov 5 21:47:56 EST 1999


Donn Cave writes:

> Quoth "Tim Peters" <tim_one at email.msn.com>:
> 
> | Let me back off to what repr and str "should do":
> |
> | repr(obj) should return a string such that
> |     eval(repr(obj)) == obj

> For real?  I'm very used to seeing repr's that don't eval at all
> -
> 
> '<socket object, fd=3, family=2, type=1, protocol=0>'
> "<open file '<stdout>', mode 'w' at 80005660>"
> '<exceptions.NameError instance at 80048ae0>'

import StringIO
x = ['a', 1, 'b', {'x':(4,5L),'z':None}]
f = StringIO.StringIO()
f.write(repr(x))
y = eval(f.getvalue())
if y == x:
  print "You betcha"

I've even been known to implement __repr__ in classes and C 
extension types so this property holds true, and I've been 
bitten by the fact that UserList just forwards repr to self.data.

- Gordon




More information about the Python-list mailing list