When __repr__() is called?
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']
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 eval
ed 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>'
>>>