Skip to content

Async queries

AsyncFlpIt is to async for what FlpIt is to for: a lazy query over an async stream. It is the counterpart of .NET's IAsyncEnumerable<T> and .NET 10's System.Linq.AsyncEnumerable. It wraps any async iterable (such as an async generator or another AsyncFlpIt) or sync iterable, runs on the task runtime, and is consumed with async for.

A first pipeline

@async_flpit turns an async generator function into one that returns an AsyncFlpIt (C#'s async IAsyncEnumerable<T> method). Callbacks can be plain functions or async def functions that take the CancellationToken as their last argument:

from flpit import async_flpit, flp
from flpit.task import CancellationToken, Task


@async_flpit                                   # C#: async IAsyncEnumerable<int> Pages(...)
async def pages(token: CancellationToken = CancellationToken.none()):
    for page in range(1, 6):
        await Task.delay(0.01, token=token)    # the enumeration's token reaches the producer
        yield page


async def is_odd(page: int, token: CancellationToken) -> bool:   # an async predicate
    return page % 2 == 1


query = pages().where(is_odd).select(lambda page: page * 10)   # nothing has run yet


async def main() -> None:
    async for item in query:                   # C#: await foreach
        assert item in (10, 30, 50)

    assert await query.to_list() == [10, 30, 50]   # terminal operators return a Task
    assert await query.first() == 10


Task.run(main).result()
  • Intermediate operators (where, select, ...) never touch the source. Each enumeration enumerates it again, and one-shot sources stay one-shot.
  • Terminal operators (to_list, first, single, count, any, sum, min_by, to_dictionary, to_lookup, aggregate, ...) return a Task. await it inside the runtime, or call .result() from synchronous code. Argument errors are raised immediately, before the Task exists.
  • flp.ait(source) wraps any async or sync iterable, and FlpIt.to_async_enumerable() converts a sync query. AsyncFlpIt.empty(), range() and repeat() are available too.

From synchronous code

# From synchronous code, block on the Task a terminal operator returns.
assert flp.ait(range(10)).where(lambda x: x % 2 == 0).count().result() == 5

Cancellation

with_cancellation(token) binds a token to an async for loop, and terminal operators accept token=. The token reaches the producer through the token parameter of an @async_flpit function, like C#'s [EnumeratorCancellation]. As in .NET, operators pass the token on and do not poll it themselves:

from flpit.task import CancellationTokenSource, OperationCanceledError


async def cancel_demo() -> None:
    cts = CancellationTokenSource()
    seen = []

    try:
        async for page in pages().with_cancellation(cts.token):
            seen.append(page)
            cts.cancel()                       # the next Task.delay(token=...) in the producer raises
    except OperationCanceledError:
        pass

    assert seen == [1]


Task.run(cancel_demo).result()

Cleanup

C#'s await foreach always disposes the stream it iterates. FlpIt gives async for the same cleanup:

  • Every enumerator an operator opens is closed when it completes, fails or short-circuits.
  • A stream left early (break, return, an exception) is closed by the runtime right after the loop, so its finally blocks run even when they await. Nothing waits for that to finish.
  • When the cleanup must be finished at a known point, use async with query.get_async_enumerator() (C#'s await using (...) { }), or put @await_using on the consuming function (C#'s await using var).
closed: list[bool] = []


@async_flpit
async def rows():
    try:
        for row in range(10):
            yield row
    finally:
        closed.append(True)                    # e.g. release a connection


async def cleanup_demo() -> None:
    async with rows().get_async_enumerator() as items:   # C#: await using
        async for row in items:
            if row == 3:
                break

    assert closed == [True]                    # the producer's finally block has already run


Task.run(cleanup_demo).result()

Use one of the last two when you need a connection, lock or semaphore slot released before you go on.

What is not there yet

AsyncFlpIt implements the operators FlpIt has. Overloads that FlpIt lacks (index-based selectors, comparers, Range and Index arguments) are not provided yet.

More runnable programs are in examples/task/: async_enumerable.py, await_using.py and streaming.py.