repr of type and class objects
letezo at fw.hu
Fri Jan 24 22:33:37 CET 2003
I've recently faced a shortcoming of my (our :-)
favourite prog. lang. related to "repr-ing" type
and class objects. Let's define a helper function
to show the problem:
def F(o): return eval(repr(o))==o
Then try this:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in F
File "<string>", line 1
SyntaxError: invalid syntax
In the case of str(int) returning "<type 'int'>" is ok, since
str() should return human-readable representation.
But repr() should return a python expression can be
evaluated into an object with the same "value" in the
same context, so returning "<type 'int'>" is a mistake.
repr() should return just "int" to satisfy the philosophy
F(int) should return 1, since:
Generally, repr() should return the __name__ attribute if
called with a class object (not an instance of a class).
I had to solve the problem by treating type objects
specially, but it isn't an elegant solution.
I know, that fixing this problem may break some
(badly written) code, but accoring to my view, it's better
to check the type of an object by checking the return
value of type() instead of parsing the output of repr().
This could be fixed easily in version 2.3.
What do you think about this problem?
More information about the Python-list