Stop writing Python 3.5 incompatible code :-)

Chris Angelico rosuav at gmail.com
Thu Jan 14 01:36:46 EST 2016


On Thu, Jan 14, 2016 at 5:27 PM, Frank Millman <frank at chagford.com> wrote:
> Using LBYL, one would retrieve the row(s) and check the length. I found a
> way to use EAFP, as follows -
>
> cur.execute('SELECT ...')
> (row,) = cur
>
> This uses tuple unpacking, and only works if exactly one row is returned. If
> it fails it raises ValueError, but I need to know whether it failed because
> no rows were returned, or more than one row was returned. The only way I
> could figure out how to achieve this was to parse the error message.

That seems like a tricky way to do things. How about this:

cur.execute(...)
rows = iter(cur)
try:
    row = next(rows)
except StopIteration:
    # 0 rows returned
try:
    next(rows)
except StopIteration: pass
else:
    # >1 rows returned

It's a bit more verbose, but it's reliable. Alternatively, since you
know that a returned row will never be None:

cur.execute(...)
rows = iter(cur)
row, extra = next(rows), next(rows)
if row is None:
    # 0 rows returned
if extra is not None:
    # >1 rows returned

ChrisA



More information about the Python-list mailing list