async def main() -> IOResultE[Sequence[str]]: """ Main entrypoint for the async world. Let's fetch 3 titles of posts asynchronously. We use `gather` to run requests in "parallel". """ futures: Sequence[IOResultE[str]] = await asyncio.gather(*_show_titles(3)) return Fold.collect(futures, IOResultE.from_value(()))
def _show_titles( number_of_posts: int, ) -> RequiresContextFutureResultE[Sequence[str], httpx.AsyncClient]: def factory(post: _Post) -> str: return post['title'] titles = [ # Notice how easily we compose async and sync functions: _fetch_post(post_id).map(factory) # TODO: try `for post_id in (2, 1, 0):` to see how errors work for post_id in range(1, number_of_posts + 1) ] return Fold.collect(titles, RequiresContextFutureResultE.from_value(()))
def test_fold_collect(iterable, sequence): """Iterable for regular types and ``Fold``.""" assert Fold.collect(iterable, sequence.from_value(())) == sequence
def test_fold_collect_recursion_limit(): """Ensures that ``.collect`` method is recurion safe.""" limit = sys.getrecursionlimit() + 1 iterable = (IO(1) for _ in range(limit)) expected = IO((1, ) * limit) assert Fold.collect(iterable, IO(())) == expected
def test_fold_collect_reader(iterable, sequence): """Ensures that ``.collect`` works for readers.""" assert Fold.collect( iterable, sequence.from_value(()), )(...) == sequence(...)