DEV Community

Cover image for ༄ streamable: if Python's stdlib got sync/async concurrent iterable streams
Enzo Bonnal
Enzo Bonnal

Posted on

༄ streamable: if Python's stdlib got sync/async concurrent iterable streams

Hi! streamable is my attempt at providing the Python ecosystem with stdlib-grade sync/async concurrent iterable streams.

"stdlib-grade" is bold, I know; here is what it means to me:

  • intuitive: a small surface of carefully named methods and params, so that reviewers barely need to learn anything to understand what is going on.
  • composable: operations provide few atomic behaviors, and most of the complex use cases can be tackled by composing them.
  • robust: a large test matrix (CPython 3.8 to 3.15 and 3.14 free-threaded, PyPy, Linux/Windows/macOS, asyncio/uvloop), a regression test for every fix, full branch coverage, thorough documentation.

▼ what is streamable

Only one import: stream[T], wrapping any Iterable[T]/AsyncIterable[T] (or function) with a lazy fluent interface exposing:

  • .map: (concurrent) transformations
  • .do: (concurrent) side effects
  • .group: batching (by key, within a time window)
  • .flatten: (concurrent) un-batching
  • .filter: element selection
  • .take: restrict to leading elements
  • .skip: ignore leading elements
  • .catch: error handling
  • .throttle: rate limiting
  • .buffer: background pre-fetch
  • .observe: iteration progress monitoring

And that's it. The stream's source/consumption and retries are not its responsibility: it's meant to be combined with dedicated builtins and libraries, e.g. collect via list/set, reduce via functools.reduce, retry via tenacity, read/write via pyarrow, psycopg, boto3, dlt.

Every stream is both Iterable and AsyncIterable; its operations accept both sync and async functions and adapt their behavior to the type of iteration.

▼ example: extract pokemons

pip install streamable==2.1.0 (no dependencies)

import logging
from datetime import timedelta
from httpx import AsyncClient, HTTPStatusError, Response, get
from streamable import stream
Enter fullscreen mode Exit fullscreen mode

sync:

pokemons: stream[str] = (
    stream(range(10))
    .map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
    .throttle(5, per=timedelta(seconds=1))
    .map(get, concurrency=2)
    .do(Response.raise_for_status)
    .observe("responses")
    .catch(HTTPStatusError, do=logging.warning)
    .map(lambda poke: poke.json()["name"])
    .observe("pokemons")
)

assert list(pokemons) == [
    'bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise'
]
Enter fullscreen mode Exit fullscreen mode

async, same code, just with an async HTTP client:

async with AsyncClient() as async_http:
    pokemons: stream[str] = (
        stream(range(10))
        .map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
        .throttle(5, per=timedelta(seconds=1))
        .map(async_http.get, concurrency=2)
        .do(Response.raise_for_status)
        .observe("responses")
        .catch(HTTPStatusError, do=logging.warning)
        .map(lambda poke: poke.json()["name"])
        .observe("pokemons")
    )

    assert [pokemon async for pokemon in pokemons] == [
        'bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise'
    ]
Enter fullscreen mode Exit fullscreen mode

async from a sync context:

import asyncio

with asyncio.Runner() as runner:
    async_http = AsyncClient()
    pokemons: stream[str] = (
        stream(range(10))
        .map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
        .throttle(5, per=timedelta(seconds=1))
        .map(async_http.get, concurrency=2)
        .do(Response.raise_for_status)
        .observe("responses")
        .catch(HTTPStatusError, do=logging.warning)
        .map(lambda poke: poke.json()["name"])
        .observe("pokemons")
    )

    assert list(pokemons) == [
        'bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise'
    ]
    runner.run(async_http.aclose())
Enter fullscreen mode Exit fullscreen mode

▼ use cases

Devs dealing with single-node processing can delegate some plumbing to streamable, keeping their code concise and clear, e.g.:

  • LLM/API enrichment
  • web scraping
  • DB/file transfers
  • event queue consumption
  • batched CPU-bound processing
  • ETL / reverse ETL

I'll write about these use cases in more detail soon.

▼ comparison

There are many libraries that look similar to streamable (e.g. pypeln, aiostream, RxPY, PyFunctional, streamz, pipe), but to my knowledge none of them offers at the same time:

  • a unified sync/async interface.
  • a typed fluent interface designed for Python, not porting idioms from other languages / paradigms.
  • operations focused on stream transformations, delegating opinionated source/consumption/retries.
  • resilient iteration: An exception raised during a stream's iteration doesn't break it: you can keep iterating.
  • robustness locked into rigorous unit tests (e.g. surviving mid-pull KeyboardInterrupt/asyncio.CancelledError, no refcycles from raised exceptions) run on a large test matrix.
  • structured concurrency via .close/.aclose on stream's iterators.
  • builtins-level performance on simple map/filter: iter(stream(range(8)).filter(lambda n: n % 2).map(str)) matching exactly the performance of map(str, filter(lambda n: n % 2, range(8))).
  • a pretty repr?

streamable is not relevant when distributed processing or advanced functional programming features are needed. Also for simple use cases, you may not find it worth adding another dependency to your project if loops, comprehensions, stdlib's itertools and Executor.map (with the new buffersize param I contributed to 3.14) are enough, but that's a matter of taste.


2.1.0 is now out (thanks to the contributors!). It brings support for structured concurrency among other things: changelog.

Whether you're curious how it compares to another lib, about the internals, a use case, or anything else, let's discuss in the comments. Thanks for your attention!

GitHub logo ebonnal / streamable

sync/async concurrent iterable streams for Python

This library is human-implemented, AI is only used for bug-hunting, mechanical edits and line completion.

༄ streamable

sync/async concurrent iterable streams

stream[T] wraps any Iterable[T] or AsyncIterable[T] with a lazy fluent interface covering concurrency, batching, buffering, rate limiting, progress observation, and error handling.

Python 3.8+ PyPI version Anaconda-Server Badge branch coverage readthedocs

1. install

pip install streamable==2.1.0

No dependencies.

Tested on Linux/Windows/macOS, CPython 3.8 to 3.15 and 3.14t (free-threaded), PyPy, uvloop.

2. import

from streamable import stream
Enter fullscreen mode Exit fullscreen mode

3. init

Create a stream[T] from an Iterable[T] or AsyncIterable[T] (or a function):

ints: stream[int] = stream(range(10))
Enter fullscreen mode Exit fullscreen mode

4. operate

Chain lazy operations (accepting sync and async functions):

# sync GET
import logging
from datetime import timedelta
from httpx import HTTPStatusError, Response, get

pokemons: stream[str] = (
    stream(range(10))
    .map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i
…
Enter fullscreen mode Exit fullscreen mode

Top comments (0)