ebonnal/streamable
Sobre
sync/async concurrent iterable streams for Python
Dados e análiseCrescimento medido de estrelas
- em 24 h
- +1
- em 7 dias
- +1
- em 15 dias
- 0
- em 1 mês
- +3
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
OriginalThis 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.
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
3. init
Create a stream[T] from an Iterable[T] or AsyncIterable[T] (or a function):
ints: stream[int] = stream(range(10))
4. operate
Chain lazy operations:
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}")
.throttle(5, per=timedelta(seconds=1))
.map(get, concurrency=2) # or an httpx.AsyncClient()'s get
.do(Response.raise_for_status)
.catch(HTTPStatusError, do=logging.warning)
.map(lambda poke: poke.json()["name"])
)
Each operation returns a new stream, and source elements are processed on-the-fly during iteration.
5. iterate
A stream[T] is Iterable[T] and AsyncIterable[T]:
>>> list(pokemons)
['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']
>>> [pokemon async for pokemon in pokemons]
['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']
core principles
focused: A stream exposes operations to manipulate its elements, but its 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: check the recipes.
sync/async:
Operations accept both sync and async functions (recognised if defined via
async defor marked viainspect.markcoroutinefunction).A
streamsupports both sync and async iteration (e.g.forandasync for), and operations adapt their behavior.A sync iteration over a
streaminvolving async functions or anAsyncIterablesource runs as an async iteration under the hood, using the current event loop if one is set.
resilient: An exception raised during a stream's iteration doesn't break it: you can keep iterating (until it is exhausted or closed).
structured concurrency: The iterators returned by stream.__iter__/stream.__aiter__ expose a .close/.aclose method to eagerly terminate the tasks/threads they may spawn during iteration.
match builtins: Iteration over stream(source).filter(pred).map(into) introduces zero overhead vs builtins-based map(into, filter(pred, source)).
operations (docs)
.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
▼ .map
Transform elements:
int_chars: stream[str] = stream(range(10)).map(str)
assert list(int_chars) == ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
concurrency
Set the concurrency param to apply the transformation concurrently, preserving upstream order unless you set as_completed=True.
Only about concurrency upstream elements are in-flight for processing: an upstream element is only pulled right before yielding the next result. If the upstream is slow, that can delay the yielding of already available results, unless you place a .buffer directly before this .map to decouple upstream and downstream rates.
Check .close/.aclose for structured concurrency.
via threads
If concurrency > 1, the transformation will be applied via concurrency threads:
from httpx import get
pokemons: stream[str] = (
stream(range(1, 4))
.map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
.map(get, concurrency=2)
.map(lambda poke: poke.json()["name"])
)
assert list(pokemons) == ['bulbasaur', 'ivysaur', 'venusaur']
via async
If concurrency > 1 and the transformation is async, it will be applied via concurrency async tasks:
from httpx import AsyncClient
# async context
async with AsyncClient() as async_http:
pokemons: stream[str] = (
stream(range(1, 4))
.map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
.map(async_http.get, concurrency=2)
.map(lambda poke: poke.json()["name"])
)
assert [name async for name in pokemons] == ['bulbasaur', 'ivysaur', 'venusaur']
import asyncio
from httpx import AsyncClient
# sync context
with asyncio.Runner() as runner:
async_http = AsyncClient()
pokemons: stream[str] = (
stream(range(1, 4))
.map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
.map(async_http.get, concurrency=2)
.map(lambda poke: poke.json()["name"])
)
# uses runner's loop
assert list(pokemons) == ['bulbasaur', 'ivysaur', 'venusaur']
runner.run(async_http.aclose())
via processes
concurrency can also be a concurrent.futures.Executor, pass a ProcessPoolExecutor to apply the transformations via processes:
from concurrent.futures import ProcessPoolExecutor
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=10) as processes:
state: list[int] = []
# ints are mapped
assert list(
stream(range(10))
.map(state.append, concurrency=processes)
) == [None] * 10
# the `state` of the main process is not mutated
assert state == []
▼ .do
Perform side effects:
state: list[int] = []
storing_ints: stream[int] = stream(range(10)).do(state.append)
assert list(storing_ints) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
assert state == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
concurrency
Same as .map.
▼ .group
Group elements into batches...
... up_to a given batch size:
int_batches: stream[list[int]] = stream(range(10)).group(5)
assert list(int_batches) == [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
... within a given time interval:
from datetime import timedelta
int_1s_batches: stream[list[int]] = (
stream(range(10))
.throttle(2, per=timedelta(seconds=1))
.group(within=timedelta(seconds=0.99))
)
assert list(int_1s_batches) == [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
... by a given key, yielding (key, elements) pairs:
ints_by_parity: stream[tuple[str, list[int]]] = (
stream(range(10))
.group(by=lambda n: "odd" if n % 2 else "even")
)
assert list(ints_by_parity) == [("even", [0, 2, 4, 6, 8]), ("odd", [1, 3, 5, 7, 9])]
You can combine these parameters.
▼ .flatten
Explode upstream elements (Iterable or AsyncIterable):
chars: stream[str] = stream(["hel", "lo!"]).flatten()
assert list(chars) == ["h", "e", "l", "l", "o", "!"]
concurrency
Explode concurrency iterables at a time, yielding elements in a round-robin manner, or as they become available if as_completed=True.
chars: stream[str] = stream(["hel", "lo", "!"]).flatten(concurrency=2)
assert list(chars) == ["h", "l", "e", "o", "l", "!"]
▼ .filter
Filter elements satisfying a predicate:
even_ints: stream[int] = stream(range(10)).filter(lambda n: n % 2 == 0)
assert list(even_ints) == [0, 2, 4, 6, 8]
▼ .take
Take a given number of elements:
first_5_ints: stream[int] = stream(range(10)).take(5)
assert list(first_5_ints) == [0, 1, 2, 3, 4]
... or take until a predicate is satisfied:
first_5_ints: stream[int] = stream(range(10)).take(until=lambda n: n == 5)
assert list(first_5_ints) == [0, 1, 2, 3, 4]
▼ .skip
Skip a given number of elements:
ints_after_5: stream[int] = stream(range(10)).skip(5)
assert list(ints_after_5) == [5, 6, 7, 8, 9]
... or skip until a predicate is satisfied:
ints_after_5: stream[int] = stream(range(10)).skip(until=lambda n: n >= 5)
assert list(ints_after_5) == [5, 6, 7, 8, 9]
▼ .catch
Catch exceptions of a given type:
inverses: stream[float] = (
stream(range(10))
.map(lambda n: round(1 / n, 2))
.catch(ZeroDivisionError)
)
assert list(inverses) == [1.0, 0.5, 0.33, 0.25, 0.2, 0.17, 0.14, 0.12, 0.11]
... where a predicate is satisfied:
from http import HTTPStatus
from httpx import HTTPStatusError, Response, get
urls = [
"https://github.com/ebonnal",
"https://github.com/ebonnal/streamable",
"https://github.com/ebonnal/foo",
]
responses: stream[Response] = (
stream(urls)
.map(get)
.do(Response.raise_for_status)
.catch(
HTTPStatusError,
where=lambda e: e.response.status_code == HTTPStatus.NOT_FOUND,
)
)
assert len(list(responses)) == 2
... do a side effect on catch:
errors: list[Exception] = []
inverses: stream[float] = (
stream(range(10))
.map(lambda n: round(1 / n, 2))
.catch(ZeroDivisionError, do=errors.append)
)
assert list(inverses) == [1.0, 0.5, 0.33, 0.25, 0.2, 0.17, 0.14, 0.12, 0.11]
assert len(errors) == 1
... replace with a value:
inverses: stream[float] = (
stream(range(10))
.map(lambda n: round(1 / n, 2))
.catch(ZeroDivisionError, replace=lambda e: float("inf"))
)
assert list(inverses) == [float("inf"), 1.0, 0.5, 0.33, 0.25, 0.2, 0.17, 0.14, 0.12, 0.11]
... stop=True to stop the iteration if an exception is caught:
inverses: stream[float] = (
stream(range(10))
.map(lambda n: round(1 / n, 2))
.catch(ZeroDivisionError, stop=True)
)
assert list(inverses) == []
You can combine these parameters.
▼ .throttle
Limit the number of emissions per time interval (sliding window):
from datetime import timedelta
throttled_ints: stream[int] = stream(range(10)).throttle(3, per=timedelta(seconds=1))
# takes 3 seconds
assert list(throttled_ints) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
▼ .buffer
Buffer upstream elements into a bounded queue via a background task/thread (decoupling upstream production rate from downstream consumption rate):
from time import sleep
pulled: list[int] = []
buffered_ints = iter(
stream(range(10))
.do(pulled.append)
.buffer(5)
)
assert next(buffered_ints) == 0
sleep(1e-3)
assert pulled == [0, 1, 2, 3, 4, 5]
▼ .observe
Observe the iteration progress:
observed_ints: stream[int] = stream(range(10)).observe("ints")
assert list(observed_ints) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
logs:
2025-12-23T16:43:07Z INFO observed=ints elapsed=0:00:00.000019 errors=0 elements=1
2025-12-23T16:43:07Z INFO observed=ints elapsed=0:00:00.001117 errors=0 elements=2
2025-12-23T16:43:07Z INFO observed=ints elapsed=0:00:00.001147 errors=0 elements=4
2025-12-23T16:43:07Z INFO observed=ints elapsed=0:00:00.001162 errors=0 elements=8
2025-12-23T16:43:07Z INFO observed=ints elapsed=0:00:00.001179 errors=0 elements=10
Logs are produced when the counts reach powers of 2 (and at exhaustion/close). Set every to produce them periodically:
# observe every 1k elements (or errors)
observed_ints = stream(range(10)).observe("ints", every=1000)
# observe every 5 seconds
from datetime import timedelta
observed_ints = stream(range(10)).observe("ints", every=timedelta(seconds=5))
Observations are logged via logging.getLogger("streamable").info. Set do to do something else with the streamable.Observation:
observed_ints = stream(range(10)).observe("ints", do=custom_logger.info)
observed_ints = stream(range(10)).observe("ints", do=observations.append)
observed_ints = stream(range(10)).observe("ints", do=print)
••• other notes
function as source
A stream can also be instantiated from a function (sync or async) that will be called sequentially to get the next element, until it raises StopIteration (or StopAsyncIteration if async).
e.g. stream from a Queue:
from queue import Queue
# or from asyncio import Queue
ints_queue: Queue[int] = ...
ints: stream[int] = stream(ints_queue.get)
To stop on a sentinel value, either:
- add
.take(until=lambda _: _ is sentinel) - or use
stream(iter(ints_queue.get, sentinel))(sync only)
+ concatenation
Concatenate a stream with another iterable:
concatenated_ints: stream[int] = stream(range(5)) + range(5, 10)
assert list(concatenated_ints) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.cast elements
Provide a type hint for elements:
import json
dicts: stream[dict[str, str]] = (
stream(['{"foo": "bar"}', '{"foo": "baz"}'])
.map(json.loads) # stream[Any]
.cast(dict[str, str])
)
.__call__ a stream
Iterate as an Iterable until exhaustion, without collecting its elements:
state: list[int] = []
pipeline: stream[int] = stream(range(10)).do(state.append)
pipeline()
assert state == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
await a stream
Iterate as an AsyncIterable until exhaustion, without collecting its elements:
state: list[int] = []
pipeline: stream[int] = stream(range(10)).do(state.append)
await pipeline
assert state == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.pipe
Apply a callable, passing the stream as first argument, followed by the provided *args and **kwargs:
import polars as pl
pokemons: stream[str] = ...
pokemons.pipe(pl.DataFrame, schema=["name"]).write_csv("pokemons.csv")
starmap
The star function decorator transforms a function (sync or async) that takes several positional arguments into a function that takes a tuple.
from streamable import star
pokemons: stream[str] = ... # see top of the README
enumerated_pokes: stream[str] = (
stream(enumerate(pokemons))
.map(star(lambda index, poke: f"#{index + 1} {poke}"))
)
assert list(enumerated_pokes) == ['#1 bulbasaur', '#2 ivysaur', '#3 venusaur', '#4 charmander', '#5 charmeleon', '#6 charizard', '#7 squirtle', '#8 wartortle', '#9 blastoise']
distinct
To collect distinct elements you can set(a_stream).
To deduplicate in the middle of the stream, .filter new values and .do add them into a set (or a fancier cache):
seen: set[str] = set()
unique_ints: stream[int] = (
stream("001000111")
.filter(lambda _: _ not in seen)
.do(seen.add)
.map(int)
)
assert list(unique_ints) == [0, 1]
structured concurrency
During an iteration, these operations spawn child tasks/threads:
.map/.do/.flattenwithconcurrency > 1.buffer.group(..., within=timedelta(...)).observe(..., every=timedelta(...))
When the iteration is complete, all the child tasks/threads are done.
When the iterator is destroyed before exhaustion, the pending work is cancelled if possible.
stream.__iter__/stream.__aiter__ returns an Iterator/AsyncIterator with a retriable .close/.aclose method to eagerly terminate any pending child tasks/threads.
.close
import time
from contextlib import closing
s = stream(range(10)).do(time.sleep, concurrency=4)
with closing(iter(s)) as it:
assert next(it) == 0
assert next(it) == 1
# 4 worker threads processing elements 2, 3, 4, 5
# work done/cancelled and worker threads terminated
equivalent to:
import time
from streamable import stream_iterator
s = stream(range(10)).do(time.sleep, concurrency=4)
it: stream_iterator[int] = iter(s)
try:
assert next(it) == 0
assert next(it) == 1
# 4 worker threads processing elements 2, 3, 4, 5
finally:
it.close()
# work done/cancelled and worker threads terminated
.aclose
import asyncio
from contextlib import aclosing
s = stream(range(10)).do(asyncio.sleep, concurrency=4)
async with aclosing(aiter(s)) as it:
assert await anext(it) == 0
assert await anext(it) == 1
# 4 pending tasks, for elements 2, 3, 4, 5
# these 4 tasks are done/cancelled
equivalent to:
import asyncio
from streamable import stream_aiterator
s = stream(range(10)).do(asyncio.sleep, concurrency=4)
it: stream_aiterator[int] = aiter(s)
try:
assert await anext(it) == 0
assert await anext(it) == 1
# 4 pending tasks, for elements 2, 3, 4, 5
finally:
await it.aclose()
# these 4 tasks are done/cancelled
recipes
Check recipes for use case patterns:
mentions
Explore projetos relacionados
Carregando…