__repr__ policy problem: should module be prefixed to output?

Remco Gerlich scarblac at pino.selwerd.nl
Tue Dec 19 05:13:42 EST 2000


A.M. Kuchling <amk at mira.erols.com> wrote in comp.lang.python:
> On Sat, 16 Dec 2000 00:41:59 +0200, Pearu Peterson <pearu at cens.ioc.ee> wrote:
> >Are there any better solutions to the repr string dilemma?
> 
> Yes: remove the text from the Tutorial (or wherever it is) that says
> that eval(repr(obj)) == obj.  It's true for strings, integers, and
> floats; it's not true for instances:
> 
> >>> class C: pass
> ...
> >>> c=C() ; print repr(C)
> <class __main__.C at 0x810af9c>
> >>>

But it *couldn't* be true for classes. And although it's possible to have
the instance return "C()", that wouldn't necessarily recreate an object of
the same value, and that problem can't be solved automatically.

> Practically no objects are so simple that the repr() could encapsulate
> all their state; how can repr(file_object) produce something useful?

File objects can't. The rule only states that it should produce something
useful if it can.

> If you really want to represent an object as a string for future
> recreation, pickle it.

You can't inspect and change pickles by hand.

> Frankly, the only place I ever use repr() is in debugging print
> statements and log files, where I need to be very clear about what an
> object is and avoid confusing the integer 1 with the string '1'.  I
> therefore write __repr__ on classes to be as useful for debugging
> purposes as possible; it doesn't recurse into subobjects, but does
> include the class name, the id() of the object, and any other unique
> identifier for the object (an ID number, user name, whatever).
> 
> To put my money where my mouth is, I'd like to file a documentation
> bug about this.  What bits of the Python documentation promote this
> view of repr()?  One is section 3 of the reference guide, in its
> description of the __repr__ special method name; any others?

What is the bug, precisely? You never use it?

The language reference has it when in the description of __repr__, and
the library reference in the description of repr().

This is only really an issue with instances, since you get to make your
own __repr__ for those. And in my experience, it is usually quite possible
to return a string that could be used to build the object again (for instance,
by giving the right arguments to the constructor). Of course, if you
have objects with lots of subobjects and so on, it may not be feasible
and you don't use it.

But I still like the rule. And, well, it's what repr does.

-- 
Remco Gerlich



More information about the Python-list mailing list