Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #102302
| From | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Cannot step through asynchronous iterator manually |
| Date | 2016-01-30 13:04 +0000 |
| Message-ID | <mailman.128.1454159539.2338.python-list@python.org> (permalink) |
| References | <n8hjmt$b8n$1@ger.gmane.org> <CALwzid=sSDSm8hdAN+ORJ54A_jEu9Wc8103iqGKAah8mrj-TXw@mail.gmail.com> <n8hrs1$orn$1@ger.gmane.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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Cannot step through asynchronous iterator manually Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-01-30 13:04 +0000
csiph-web