print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().
views:
116answers:
4
+7
A:
repr(obj)
calls
obj.__repr__
the purpose of __repr__ is that it provides a 'formal' representation of the object that is supposed to be a expression that can be evaled to create the object. that is,
obj == eval(repr(obj))
should, but does not always in practice, yield True
I was asked in the comments for an example of when obj != eval(repr(obj)).
class BrokenRepr(object):
def __repr__(self):
return "not likely"
here's another one:
>>> con = sqlite3.connect(':memory:')
>>> repr(con)
'<sqlite3.Connection object at 0xb773b520>'
>>>
aaronasterling
2010-09-21 20:49:16
Why does obj == eval(repr(obj)) not always give True? Would you be able to give an example?
inspectorG4dget
2010-09-21 21:44:24
For a complex object, such as a file, it will not necessarily return True.
Avi
2010-09-21 21:50:36
@inspectorG4dget: obj == eval(type('myclass', (), {}))
Mike Axiak
2010-09-21 21:51:17
Many thanks @AaronMcSmooth, @Avi, @MikeAxiak for explaining this. ++ to all
inspectorG4dget
2010-09-21 22:02:59
A:
repr(obj) calls obj.__repr__.
This is intended to clearly describe an object, specially for debugging purposes. More info in the docs
Flávio Amieiro
2010-09-21 20:52:18
@S.Lott thanks for pointing out my markup mistake, it's fixed now. I just don't know which guidelines you're referring to.
Flávio Amieiro
2010-09-21 23:19:59
A:
In python 2.x, `obj` will end up calling obj.__repr__(). It's shorthand for repr().
recursive
2010-09-21 21:13:37
+3
A:
Not only does repr get called when you use repr(), but also in the following cases:
- You type obj in the shell and press enter.
- You ever print an object in a dictionary/tuple/list. E.g.: print [u'test'] does not print ['test']
Mike Axiak
2010-09-21 21:52:29