Good or bad use of __repr__?

Stephen Hansen apt.shansen at gmail.com
Tue Feb 3 23:23:40 EST 2009


>
> As written, if a program references a Dimension instance without an
> attribute, it gets the size attrbute "by default". If it wants the other
> attributes, they have to be spec'd. In the context of the code being
> developed, the "size" attribute is the "logical" representation of the
> dimension. I'm just wondering if this sort of design should be avoided.

Well the question is: does that repr give you sufficient information
to identify at least and possibly recreate that instance?

If you repr an int and it comes up as 50.. and repr a Dimension and it
comes up as 50, does that allow you to differentiate between them? If
you need to. I primarily use repr for a debugging tool, and in that
context I'd always for instances at least make it something like
<Dimension(size=50)> as the repr output. But I personally like to err
on the side of 'more is better' when it comes to repr output, and
would probably have put in the name/unlimited/coord even if they may
not always be present. So that if you're checking something after the
fact and all you have to go on is a repr of an object involved you
have more details to work with.

But there's no hard and fast rules. Generally, repr output should be
whatever you need to clearly reflect The Specific Object as a string.

--S



More information about the Python-list mailing list