Cannot step through asynchronous iterator manually
Oscar Benjamin
oscar.j.benjamin at gmail.com
Sat Jan 30 09:11:40 EST 2016
On 30 January 2016 at 13:45, Frank Millman <frank at chagford.com> wrote:
> "Oscar Benjamin" wrote in message
> news:CAHVvXxSA0Yq4VOYy6qycgXxVpL5zZGM8muUi+1VmeZD8CRgtvg at mail.gmail.com...
>>
>>
>> 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]
>>
>
> I like the idea, but I don't think it would work with an asychronous
> iterable.
That was intended as an improvement over the code that you posted for
normal iterators.
> OTOH it should not be difficult to roll your own using the example
> in the itertools docs as a base. Except that the example uses next(it)
> internally, and this thread started with the fact that there is no
> asychronous equivalent, so I might be back to square one.
I haven't used PEP 492 yet but what about:
async def aslice(asynciterator, end):
if end == 0:
return []
items = []
async for item in asynciterator:
items.append(item)
if len(items) == end:
break
return items
rows = await aslice(cur, 2)
AFAICT there's no generator-function-style syntax for writing an async
iterator so you'd have to make a class with the appropriate methods if
you wanted to be able to loop over aslice with async for.
--
Oscar
More information about the Python-list
mailing list