Is this pythonic?

Chris Angelico rosuav at gmail.com
Wed Nov 23 08:01:07 EST 2016


On Wed, Nov 23, 2016 at 11:27 PM, Frank Millman <frank at chagford.com> wrote:
>
> @Chris
>>
>> This strongly suggests that str(x) is the wrong way to get the
>> information. You shouldn't be doing database requests inside __str__
>> or __repr__.
>
>
> I guess you are right, but still it is a pity. __str__ has been working for
> me beautifully for a long time now. The only change is that, previously, all
> the values had been read in or computed before calling __str__(), now I am
> delaying the computation until requested.
>
> It is a bit like quantum theory. I have no way of telling whether the
> computation has been carried out without looking at it, but the act of
> looking at it triggers the computation. I can tell, of course, by looking at
> the underlying attribute, but not by using the public methods.

That makes sense. What you could do is have __repr__ do something like this:

def __repr__(self):
    if self.has_data:
        return "<%s: %r>" % (self.col_name, self.data)
    return "<%s: <not fetched> >" % self.col_name

I'm not sure that that would be appropriate for __str__, though; maybe
it could return the string of data if it exists, otherwise it could
fall back on __repr__?

ChrisA



More information about the Python-list mailing list