As the Python 2 documentation on __repr__
states:
If at all possible, this (i.e.
__repr__
) should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
So how come builtin __repr__
for classes does not act accordingly to that guideline?
Example
>>> class A(object):
... pass
>>> repr(A)
"<class 'A'>"
To meet the guideline, the default __repr__
should return "A"
, i.e. generally A.__name__
. Why is it acting differently? It would be extra-easy to implement, I believe.
Edit: The scope of 'reproduction'
I can see in the answers that it is not clear in the discussion what repr
should return. The way I see it, the repr
function should return a string that allows you to reproduce the object:
- in an arbitrary context and
- automatically (i.e. not manually).
Ad.1. Take a look at a built-in class case (taken from this SO question):
>>> from datetime import date
>>>
>>> repr(date.today()) # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
Apparently, the assumed context is as if you use the basic form of import, i.e. import datetime
, because if you would try eval(repr(date.today()))
, datetime
would not be recognized. So the point is that __repr__
doesn't need to represent the object from scratch. It's enough if it is unambiguous in a context the community agreed upon, e.g. using direct module's types and functions. Sounds reasonable, right?
Ad.2. Giving an impression of how the object could be reconstructed is not enough for repr
, I believe. Helpfulness in debugging is the purpose of str
.
Conclusion
So what I expect from repr
is allowing me to do eval
on the result. And in the case of a class, I would not like to get the whole code that would reconstruct the class from scratch. Instead, I would like to have an unambiguous reference to a class visible in my scope. The "Module.Class"
would suffice. No offence, Python, but "<class 'Module.Class'>"
doesn't just cut it.