repr of type and class objects

Létezo letezo at fw.hu
Fri Jan 24 16:33:37 EST 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:

>>> F(1)
1
>>> F('x')
1
>>> F(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 1, in F
  File "<string>", line 1
    <type 'int'>
    ^
SyntaxError: invalid syntax

>>> str(int)
"<type 'int'>"

>>> repr(int)
"<type 'int'>"

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
behind repr.

F(int) should return 1, since:

>>> int==int
1

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?

Best regards,
Complex








More information about the Python-list mailing list