Is this pythonic?

Chris Angelico rosuav at gmail.com
Wed Nov 23 06:22:53 EST 2016


On Wed, Nov 23, 2016 at 10:11 PM, Frank Millman <frank at chagford.com> wrote:
> Gah! The law of unintended consequences strikes again!
>
> As I mentioned, the class in question represents a database column. A
> separate class represents a database row. I have a __str__() method on the
> 'row' class that prints a nicely formatted representation of the object with
> all of its column objects and their values.
>
> With the above changes, I had to turn getval() into a coroutine. My
> __str__() method uses getval() to obtain the values, so I had to prefix
> getval() with 'await', but then I get a syntax error on __str__(). I can add
> 'async' to remove the syntax error, but then print(obj) does not work -
> TypeError: __str__ returned non-string (type coroutine)
>
> I don't think there is an answer to this, but any suggestions will be
> appreciated.
>
> I can say 'print(await obj.__str__())', and it works, but I lose the ability
> to include it in a larger print statement.
>
> Ah well :-(

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__.

ChrisA



More information about the Python-list mailing list