Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #102302 > unrolled thread

Re: Cannot step through asynchronous iterator manually

Started byOscar Benjamin <oscar.j.benjamin@gmail.com>
First post2016-01-30 13:04 +0000
Last post2016-01-30 13:04 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Cannot step through asynchronous iterator manually Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-01-30 13:04 +0000

#102302 — Re: Cannot step through asynchronous iterator manually

FromOscar Benjamin <oscar.j.benjamin@gmail.com>
Date2016-01-30 13:04 +0000
SubjectRe: Cannot step through asynchronous iterator manually
Message-ID<mailman.128.1454159539.2338.python-list@python.org>
On 30 January 2016 at 08:22, Frank Millman <frank@chagford.com> wrote:
> There are times when I want to execute a SELECT statement, and test for
> three possibilities -
>    - if no rows are returned, the object does not exist
>    - if one row is returned, the object does exist
>    - if more that one row is returned, raise an exception
>
> We had a recent discussion about the best way to do this, and ChrisA
> suggested the following, which I liked -
>
>    cur.execute('SELECT ...)
>    try:
>        row = next(cur)
>    except StopIteration:
>        # row does not exist
>    else:
>        try:
>            next_row = next(cur)
>        except StopIteration:
>            # row does exist
>        else:
>            # raise exception

The simplest thing would just be to call list(cur) but I realise that
you don't want to consume more than 2 rows from the database so just
use islice:

rows = list(islice(cur, 2))  # pull at most 2 rows
if not rows:
    # no rows
elif len(rows) > 1:
    # too many rows
row = rows[0]

Depending on your application if you just want to raise any error when
there's not exactly one row then you could just do:

(row,) = list(islice(cur, 2))

--
Oscar

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web