Stop writing Python 3.5 incompatible code :-)

Frank Millman frank at chagford.com
Thu Jan 14 04:39:05 EST 2016


"Frank Millman"  wrote in message news:n77j78$ld0$1 at ger.gmane.org...

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

For the record, I just tried this and found an error.

It is easier to explain if I change it slightly -

cur.execute(...)
try:
    row = next(cur)
except StopIteration:
    # 0 rows returned
try:
    next(cur)
except StopIteration:
    # instead of pass, do something with row
else:
    # >1 rows returned

'do something with row' is reached even if the first next() failed, so row 
does not exist.

Here is the corrected version -

cur.execute(...)
try:
    row = next(cur)
except StopIteration:
    # 0 rows returned
else:
    try:
        next(cur)
    except StopIteration:
        # do something with row
    else:
        # >1 rows returned

Frank





More information about the Python-list mailing list