← Back to team overview

launchpad-dev team mailing list archive

Re: Give your models some repr love!

 

On 11 February 2010 17:07, Jonathan Lange <jml@xxxxxxxxxxxxx> wrote:
> On Thu, Feb 11, 2010 at 5:00 PM, Tom Berger <tom.berger@xxxxxxxxxxxxx> wrote:
>> On 11 February 2010 16:51, Barry Warsaw <barry@xxxxxxxxxxxxx> wrote:
>>> Just a quick plea:
>>>
>>> When writing new model objects, or touching existing ones, please think about
>>> given them a useful __repr__().  This can greatly improve the introspection
>>> experience when using pdb or 'make harness'.
>>>
>>> Many/most of our model classes have no repr which means when you look at an
>>> object you get unhelpful output:
>>>
>>>    >>> ls = getUtility(ILanguageSet)
>>>    >>> ls.get(123)
>>>    <Language at 0x12345678>
>>>
>>> and then you have to find the class definition and go digging into various
>>> attributes to figure out which object you have.  Wouldn't it be much nicer to
>>> see:
>>>
>>>    >>> ls.get(123)
>>>    <Language: French (fr)>
>>>
>>> with no further effort?
>>>
>>> It's easy to do, too.  E.g. I have a branch hopefully landing soon that adds
>>> this to class Language:
>>>
>>>    def __repr__(self):
>>>        return '<Language: %s>' % self.displayname
>>>
>>> A word of warning though: adding a repr to existing classes can break doctests
>>> far from the models you're modifying, so land such branches through ec2.
>>
>> I like the example you gave above, but I have a couple of questions:
>>
>> 1. The default repr is unique. Should we try and preserve that?
>
> As a rule of thumb, I try to have repr(a) == repr(b) <==> (a == b),
> rather than (a is b). I don't know if that's standard or helps.
>
>> 2. Is there a style guide for repr?
>
> I don't know. Reckon we need one?

I feel I would like to read one before embarking on customizing repr
left and right in the Launchpad tree :) so I guess the answer is yes.
I'm sure there are also other ways to learn how write good reprs.



References