|
| 1 | +from collections.abc import AsyncIterable, Awaitable, Callable |
| 2 | +from typing import Optional, TypeVar |
| 3 | + |
| 4 | +from typing_extensions import ParamSpec, Unpack |
| 5 | + |
| 6 | +P = ParamSpec('P') |
| 7 | +R = TypeVar('R') |
| 8 | +C = TypeVar('C') |
| 9 | + |
| 10 | + |
| 11 | +def iter_pages( |
| 12 | + fn: Callable[P, Awaitable[R]], |
| 13 | + cursor_param_name: str, |
| 14 | + get_cursor: Callable[[R], Optional[C]], |
| 15 | +) -> Callable[P, AsyncIterable[R]]: |
| 16 | + """ |
| 17 | + Create a function that returns an async iterator over pages from the async operation function :param:`fn`. |
| 18 | +
|
| 19 | + The returned function can be called with the same parameters as :param:`fn` (except for the cursor parameter), |
| 20 | + and returns an async iterator that yields results from :param:`fn`, handling pagination automatically. |
| 21 | +
|
| 22 | + The function :param:`fn` will be called initially without the cursor parameter and then called with the cursor parameter |
| 23 | + as long as :param:`get_cursor` can extract a cursor from the result. |
| 24 | +
|
| 25 | + **Example:** |
| 26 | +
|
| 27 | + .. code:: python |
| 28 | +
|
| 29 | + async for page in iter_pages(client.fn, 'cursor', extractor_fn)(parameter=value): |
| 30 | + # Process page |
| 31 | +
|
| 32 | + Typically, an API will use the same paging pattern for all operations supporting it, so it's a good idea to write a shortcut function: |
| 33 | +
|
| 34 | + .. code:: python |
| 35 | +
|
| 36 | + from lapidary.runtime import iter_pages as _iter_pages |
| 37 | +
|
| 38 | + def iter_pages[P, R](fn: Callable[P, Awaitable[R]]) -> Callable[P, AsyncIterable[R]]: |
| 39 | + return _iter_pages(fn, 'cursor', lambda result: ...) |
| 40 | +
|
| 41 | + :param fn: An async function that retrieves a page of data. |
| 42 | + :param cursor_param_name: The name of the cursor parameter in :param:`fn`. |
| 43 | + :param get_cursor: A function that extracts a cursor value from the result of :param:`fn`. Return `None` to end the iteration. |
| 44 | + """ |
| 45 | + |
| 46 | + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> AsyncIterable[R]: |
| 47 | + result = await fn(*args, **kwargs) # type: ignore[call-arg] |
| 48 | + yield result |
| 49 | + cursor = get_cursor(result) |
| 50 | + |
| 51 | + while cursor: |
| 52 | + kwargs[cursor_param_name] = cursor |
| 53 | + result = await fn(*args, **kwargs) # type: ignore[call-arg] |
| 54 | + yield result |
| 55 | + |
| 56 | + cursor = get_cursor(result) |
| 57 | + |
| 58 | + return wrapper |
0 commit comments