flowlet 0.2.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flowlet-0.5.0/PKG-INFO ADDED
@@ -0,0 +1,301 @@
1
+ Metadata-Version: 2.4
2
+ Name: flowlet
3
+ Version: 0.5.0
4
+ Summary: A minimal async pipeline library
5
+ License-Expression: BSD-3-Clause
6
+ Requires-Python: >=3.14
7
+ Description-Content-Type: text/markdown
8
+
9
+ # flowlet
10
+
11
+ Async pipelines for Python with a concurrency limit on every stage. Zero dependencies.
12
+
13
+ Fetch 20 pages at a time, extract their links, and write them in batches of 100:
14
+
15
+ ```python
16
+ import asyncio
17
+ from flowlet import pipe
18
+
19
+
20
+ async def main() -> None:
21
+ await (
22
+ pipe(urls)
23
+ .map(fetch_page, concurrency=20)
24
+ .flat_map(extract_links, concurrency=4)
25
+ .filter(is_internal)
26
+ .batch(100)
27
+ .map(bulk_insert, concurrency=4)
28
+ .drain()
29
+ )
30
+
31
+
32
+ asyncio.run(main())
33
+ ```
34
+
35
+ - **Lazy and streaming**: nothing runs until you consume it. If the consumer falls behind, upstream stages slow down instead of buffering everything up front like `asyncio.gather`.
36
+ - **Concurrency per stage**: give each step its own limit, and opt into `ordered=True` when you need results in input order.
37
+ - **Cleans up after itself**: when a stage fails or you close the pipeline, in-flight tasks are cancelled, and the source and any iterators `flat_map` opened get closed.
38
+ - **Plays well with blocking code**: `in_thread` and `in_process` move blocking I/O and CPU work off the event loop, and `thread_local` gives each worker thread its own client.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install flowlet
44
+ ```
45
+
46
+ You'll need Python 3.14 or newer. Concurrent stages start tasks with `eager_start=True`, so any custom event loop or task factory must accept it (`uvloop` 0.23+ does).
47
+
48
+ ## Core API
49
+
50
+ | API | Purpose | Cardinality |
51
+ | :--- | :--- | :--- |
52
+ | `pipe(source)` | Start a lazy pipeline from a sync or async iterable | — |
53
+ | `.map(fn, *, concurrency=1, ordered=False)` | Transform each item (sync or async `fn`) | 1 → 1 |
54
+ | `.filter(pred, *, concurrency=1, ordered=False)` | Keep items accepted by `pred` (sync or async) | 1 → 0..1 |
55
+ | `.flat_map(fn, *, concurrency=1, buffer=256, ordered=False)` | Expand each item into an iterable or async iterable | 1 → 0..N |
56
+ | `.batch(size)` | Group items into `list`s of up to `size` | N → 1 |
57
+ | `.through(flow)` | Apply a reusable [`Flow`](#reuse-and-other-styles) | Varies |
58
+ | `.collect()` | Consume the pipeline into a `list` | Consumer |
59
+ | `.drain()` | Consume for side effects, discarding results | Consumer |
60
+ | `async for item in pipeline` | Stream results lazily | Consumer |
61
+
62
+ - **Immutable**: adding a stage returns a new `Pipeline`, so reusing one is safe. One catch: a generator or other one-shot iterator still only runs once. Run a pipeline over it twice and the second pass sees nothing.
63
+ - **`None` is just data**: stages never treat `None` as an end-of-stream sentinel. If you want `None`s gone, filter them out.
64
+
65
+ ### `flat_map` and `batch`
66
+
67
+ `flat_map(fn)` accepts a sync or async function returning any iterable or async iterable. Each expansion streams into the pipeline as its values arrive, rather than waiting to finish first.
68
+
69
+ Values flow through a bounded buffer (`256` by default) shared across expansions, plus one value per expansion waiting for room. That caps an unordered stage at `buffer + concurrency` values (see [Ordering](#ordering) for `ordered=True`). Raise `buffer` to trade memory for throughput on wide expansions:
70
+
71
+ ```python
72
+ rows = pipe(files).flat_map(parse_rows, concurrency=8, buffer=2048)
73
+ ```
74
+
75
+ `batch(size)` groups items into lists of up to `size`. If the source runs out mid-group, the last list is shorter:
76
+
77
+ ```python
78
+ await pipe([1, 2, 3, 4, 5]).batch(2).collect()
79
+ # [[1, 2], [3, 4], [5]]
80
+ ```
81
+
82
+ ### Consuming streams
83
+
84
+ Use `async for` when you don't want everything in memory at once, and always for unbounded streams, where `.collect()` would grow a list forever. `.drain()` works there too in constant memory if the stages do the useful work:
85
+
86
+ ```python
87
+ async for link in pipe(events).map(parse).filter(is_interesting):
88
+ await handle(link)
89
+ ```
90
+
91
+ If you might break out early, wrap the iterator in `contextlib.aclosing`:
92
+
93
+ ```python
94
+ from contextlib import aclosing
95
+
96
+ items = []
97
+ async with aclosing(aiter(pipe(events).map(parse, concurrency=10))) as stream:
98
+ async for item in stream:
99
+ items.append(item)
100
+ if len(items) == 100:
101
+ break
102
+ ```
103
+
104
+ A bare `break` leaves cleanup to the garbage collector, so in-flight tasks can keep running after the loop and cleanup errors won't reach you. `aclosing` shuts the pipeline down as soon as the block exits.
105
+
106
+ ## Concurrency and ordering
107
+
108
+ Each stage sets its own concurrency:
109
+
110
+ - **`concurrency=1` (default)**: one input at a time. The stage won't pull the next item until the current one's output has gone downstream.
111
+ - **`concurrency > 1`**: up to `concurrency` calls run at once. When the consumer falls behind, the stage pauses and stops pulling new input.
112
+
113
+ ### Ordering
114
+
115
+ **Concurrent stages emit results as they finish, not in input order.** Pass `ordered=True` to `map`, `flat_map`, or `filter` to keep input order without giving up concurrency:
116
+
117
+ ```python
118
+ # Completion order: may return [3, 1, 2]
119
+ items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3).collect()
120
+
121
+ # Input order: always [1, 2, 3], with three predicates running at once
122
+ items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3, ordered=True).collect()
123
+ ```
124
+
125
+ With `ordered=True`, you get the same output as `concurrency=1`: same values, same order, same ordinary failures. Only the timing changes.
126
+
127
+ Cancellation is the exception: `CancelledError` starts teardown right away in either mode. Teardown still waits for the stage's tasks, though, so a task that swallows cancellation delays it either way.
128
+
129
+ Ordering has two trade-offs:
130
+
131
+ - **Failures wait their turn**: if item 1 is slow and item 2 fails, an ordered stage waits for item 1 before raising. An unordered stage cancels pending work right away.
132
+ - **Ordered `flat_map` holds more**: each running expansion gets its own buffer, so the stage can hold up to `concurrency * (buffer + 1)` values instead of `buffer + concurrency`. Because an endless expansion blocks everything behind it, only use ordered mode for finite expansions.
133
+
134
+ ## Error handling
135
+
136
+ **Pipelines fail fast.** When a stage raises, `flowlet` cancels pending work, runs cleanup, and re-raises.
137
+
138
+ To handle per-item failures without stopping the pipeline, catch them in your function and use `.flat_map(...)` to drop failed items:
139
+
140
+ ```python
141
+ async def safe_fetch(url: str) -> list[Page]:
142
+ try:
143
+ return [await fetch(url)]
144
+ except Exception:
145
+ return []
146
+
147
+
148
+ items = await pipe(urls).flat_map(safe_fetch, concurrency=20).collect()
149
+ ```
150
+
151
+ ## Blocking work
152
+
153
+ Blocking sync code stalls the event loop. Wrap blocking I/O in `in_thread` and CPU-bound work in `in_process`.
154
+
155
+ Either way, at most `min(concurrency, max_workers)` calls run at once. Cancelling the pipeline stops waiting for a submitted call, but it can't interrupt sync code that's already running in a worker thread or process.
156
+
157
+ ### Blocking I/O with `in_thread`
158
+
159
+ `in_thread(fn, *, executor=None)` runs `fn` in a thread pool and copies `contextvars` into the worker thread. With `executor=None`, it uses asyncio's default pool:
160
+
161
+ ```python
162
+ from flowlet import in_thread, pipe
163
+
164
+ items = await pipe(keys).map(in_thread(load_s3), concurrency=64).collect()
165
+ ```
166
+
167
+ Pass your own `ThreadPoolExecutor` to cap threads or share one pool across stages:
168
+
169
+ ```python
170
+ from concurrent.futures import ThreadPoolExecutor
171
+ from flowlet import in_thread, pipe
172
+
173
+ with ThreadPoolExecutor(max_workers=16) as pool:
174
+ items = await (
175
+ pipe(keys)
176
+ .map(in_thread(load_s3, executor=pool), concurrency=8)
177
+ .map(in_thread(parse_blob, executor=pool), concurrency=4)
178
+ .collect()
179
+ )
180
+ ```
181
+
182
+ With `flat_map(in_thread(fn))`, return a `list` or `tuple`, not a lazy generator. A generator gets created on the worker thread and iterated later on the event loop, which defeats the point.
183
+
184
+ ### Per-thread resources with `thread_local`
185
+
186
+ Use `@thread_local` to create a blocking client or session once per worker thread and reuse it on every later call in that thread. A plain function works if there's nothing to clean up. For cleanup, make it a generator: `flowlet` caches the first value it yields, and the `finally` block runs on `.close()` or when the thread exits.
187
+
188
+ To control when cleanup runs, manage the `ThreadPoolExecutor` with a `with` block. When the block exits, the worker threads shut down and their clients close:
189
+
190
+ ```python
191
+ from collections.abc import Generator
192
+ from concurrent.futures import ThreadPoolExecutor
193
+ from flowlet import in_thread, pipe, thread_local
194
+
195
+
196
+ @thread_local
197
+ def session() -> Generator[HttpClient]:
198
+ client = HttpClient()
199
+ try:
200
+ yield client
201
+ finally:
202
+ # Runs once per worker thread when the pool shuts down.
203
+ client.close()
204
+
205
+
206
+ def fetch(url: str) -> Page:
207
+ return session().get(url)
208
+
209
+
210
+ with ThreadPoolExecutor(max_workers=16) as pool:
211
+ pages = await (
212
+ pipe(urls)
213
+ .map(in_thread(fetch, executor=pool), concurrency=64)
214
+ .collect()
215
+ )
216
+ ```
217
+
218
+ A few details on lifetime:
219
+
220
+ - **Explicit close**: `session.close()` closes and clears only the calling thread's instance.
221
+ - **Cleanup errors**: exceptions on thread exit go to `sys.unraisablehook`, since there's no caller left to catch them.
222
+ - **Default pool**: resources created on asyncio's default pool stay open until the pool shuts down, which with `asyncio.run` is when the event loop closes.
223
+
224
+ ### CPU-bound work with `in_process`
225
+
226
+ `in_process(fn, *, executor)` runs CPU-bound work in a `ProcessPoolExecutor`. There's no default pool, so you create one and manage its lifetime:
227
+
228
+ ```python
229
+ from concurrent.futures import ProcessPoolExecutor
230
+ from flowlet import in_process, pipe
231
+
232
+ with ProcessPoolExecutor(max_workers=8) as pool:
233
+ items = await (
234
+ pipe(keys)
235
+ .map(in_process(crunch, executor=pool), concurrency=8)
236
+ .collect()
237
+ )
238
+ ```
239
+
240
+ A few process-pool rules apply:
241
+
242
+ - **Pickling**: the worker function, its arguments, and its return value must all be picklable. Define workers at module level rather than as lambdas or local functions.
243
+ - **Start methods**: Python 3.14 defaults to `forkserver` on Linux and `spawn` on macOS and Windows. Both re-import your main module, so put script entry points behind `if __name__ == "__main__":`.
244
+ - **No `contextvars`**: unlike `in_thread`, `in_process` doesn't copy `contextvars` to worker processes.
245
+
246
+ ## Reuse and other styles
247
+
248
+ ### Reusable fragments with `Flow`
249
+
250
+ A `Flow` is a pipeline without a source. Use it to name, test, and reuse a group of stages across different pipelines:
251
+
252
+ ```python
253
+ from flowlet import Flow, pipe
254
+
255
+ extract: Flow[Page, str] = (
256
+ Flow[Page]()
257
+ .flat_map(find_links)
258
+ .filter(is_internal)
259
+ .map(normalize_url)
260
+ )
261
+
262
+ links = await pipe(pages).through(extract).collect()
263
+ ```
264
+
265
+ You can also compose flows with `.through(...)`, or run one directly on a source with `extract.apply(pages)`.
266
+
267
+ For type checking, start with `Flow[T]()` so the input type flows through every stage (`Flow[T, U]` takes `T` and produces `U`). Bare `Flow()` works too, but starts as `Flow[Any, Any]`.
268
+
269
+ ### Pipe operator (`|`) with `op`
270
+
271
+ Each function in `flowlet.op` builds a one-step `Flow`, and `|` chains them. It runs the same as method chaining, and it's handy for naming a reusable fragment without writing `Flow[T]()`:
272
+
273
+ ```python
274
+ from flowlet import op, pipe
275
+
276
+ extract = (
277
+ op.flat_map(find_links)
278
+ | op.filter(is_internal)
279
+ | op.map(normalize_url)
280
+ )
281
+
282
+ links = await (pipe(pages) | extract).collect() # same as .through(extract)
283
+ ```
284
+
285
+ ### Functional API
286
+
287
+ `flowlet.functional` exposes the curried operators behind everything above. Compose them with `chain`:
288
+
289
+ ```python
290
+ import flowlet.functional as F
291
+
292
+ process = F.chain(
293
+ F.map(fetch, concurrency=20),
294
+ F.flat_map(extract_links),
295
+ F.filter(is_valid),
296
+ )
297
+
298
+ items = await F.collect(process(urls))
299
+ ```
300
+
301
+ You can also call any operator directly: `F.map(fetch, concurrency=20)(urls)` returns an `AsyncGenerator`.
@@ -0,0 +1,293 @@
1
+ # flowlet
2
+
3
+ Async pipelines for Python with a concurrency limit on every stage. Zero dependencies.
4
+
5
+ Fetch 20 pages at a time, extract their links, and write them in batches of 100:
6
+
7
+ ```python
8
+ import asyncio
9
+ from flowlet import pipe
10
+
11
+
12
+ async def main() -> None:
13
+ await (
14
+ pipe(urls)
15
+ .map(fetch_page, concurrency=20)
16
+ .flat_map(extract_links, concurrency=4)
17
+ .filter(is_internal)
18
+ .batch(100)
19
+ .map(bulk_insert, concurrency=4)
20
+ .drain()
21
+ )
22
+
23
+
24
+ asyncio.run(main())
25
+ ```
26
+
27
+ - **Lazy and streaming**: nothing runs until you consume it. If the consumer falls behind, upstream stages slow down instead of buffering everything up front like `asyncio.gather`.
28
+ - **Concurrency per stage**: give each step its own limit, and opt into `ordered=True` when you need results in input order.
29
+ - **Cleans up after itself**: when a stage fails or you close the pipeline, in-flight tasks are cancelled, and the source and any iterators `flat_map` opened get closed.
30
+ - **Plays well with blocking code**: `in_thread` and `in_process` move blocking I/O and CPU work off the event loop, and `thread_local` gives each worker thread its own client.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install flowlet
36
+ ```
37
+
38
+ You'll need Python 3.14 or newer. Concurrent stages start tasks with `eager_start=True`, so any custom event loop or task factory must accept it (`uvloop` 0.23+ does).
39
+
40
+ ## Core API
41
+
42
+ | API | Purpose | Cardinality |
43
+ | :--- | :--- | :--- |
44
+ | `pipe(source)` | Start a lazy pipeline from a sync or async iterable | — |
45
+ | `.map(fn, *, concurrency=1, ordered=False)` | Transform each item (sync or async `fn`) | 1 → 1 |
46
+ | `.filter(pred, *, concurrency=1, ordered=False)` | Keep items accepted by `pred` (sync or async) | 1 → 0..1 |
47
+ | `.flat_map(fn, *, concurrency=1, buffer=256, ordered=False)` | Expand each item into an iterable or async iterable | 1 → 0..N |
48
+ | `.batch(size)` | Group items into `list`s of up to `size` | N → 1 |
49
+ | `.through(flow)` | Apply a reusable [`Flow`](#reuse-and-other-styles) | Varies |
50
+ | `.collect()` | Consume the pipeline into a `list` | Consumer |
51
+ | `.drain()` | Consume for side effects, discarding results | Consumer |
52
+ | `async for item in pipeline` | Stream results lazily | Consumer |
53
+
54
+ - **Immutable**: adding a stage returns a new `Pipeline`, so reusing one is safe. One catch: a generator or other one-shot iterator still only runs once. Run a pipeline over it twice and the second pass sees nothing.
55
+ - **`None` is just data**: stages never treat `None` as an end-of-stream sentinel. If you want `None`s gone, filter them out.
56
+
57
+ ### `flat_map` and `batch`
58
+
59
+ `flat_map(fn)` accepts a sync or async function returning any iterable or async iterable. Each expansion streams into the pipeline as its values arrive, rather than waiting to finish first.
60
+
61
+ Values flow through a bounded buffer (`256` by default) shared across expansions, plus one value per expansion waiting for room. That caps an unordered stage at `buffer + concurrency` values (see [Ordering](#ordering) for `ordered=True`). Raise `buffer` to trade memory for throughput on wide expansions:
62
+
63
+ ```python
64
+ rows = pipe(files).flat_map(parse_rows, concurrency=8, buffer=2048)
65
+ ```
66
+
67
+ `batch(size)` groups items into lists of up to `size`. If the source runs out mid-group, the last list is shorter:
68
+
69
+ ```python
70
+ await pipe([1, 2, 3, 4, 5]).batch(2).collect()
71
+ # [[1, 2], [3, 4], [5]]
72
+ ```
73
+
74
+ ### Consuming streams
75
+
76
+ Use `async for` when you don't want everything in memory at once, and always for unbounded streams, where `.collect()` would grow a list forever. `.drain()` works there too in constant memory if the stages do the useful work:
77
+
78
+ ```python
79
+ async for link in pipe(events).map(parse).filter(is_interesting):
80
+ await handle(link)
81
+ ```
82
+
83
+ If you might break out early, wrap the iterator in `contextlib.aclosing`:
84
+
85
+ ```python
86
+ from contextlib import aclosing
87
+
88
+ items = []
89
+ async with aclosing(aiter(pipe(events).map(parse, concurrency=10))) as stream:
90
+ async for item in stream:
91
+ items.append(item)
92
+ if len(items) == 100:
93
+ break
94
+ ```
95
+
96
+ A bare `break` leaves cleanup to the garbage collector, so in-flight tasks can keep running after the loop and cleanup errors won't reach you. `aclosing` shuts the pipeline down as soon as the block exits.
97
+
98
+ ## Concurrency and ordering
99
+
100
+ Each stage sets its own concurrency:
101
+
102
+ - **`concurrency=1` (default)**: one input at a time. The stage won't pull the next item until the current one's output has gone downstream.
103
+ - **`concurrency > 1`**: up to `concurrency` calls run at once. When the consumer falls behind, the stage pauses and stops pulling new input.
104
+
105
+ ### Ordering
106
+
107
+ **Concurrent stages emit results as they finish, not in input order.** Pass `ordered=True` to `map`, `flat_map`, or `filter` to keep input order without giving up concurrency:
108
+
109
+ ```python
110
+ # Completion order: may return [3, 1, 2]
111
+ items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3).collect()
112
+
113
+ # Input order: always [1, 2, 3], with three predicates running at once
114
+ items = await pipe([1, 2, 3]).filter(async_pred, concurrency=3, ordered=True).collect()
115
+ ```
116
+
117
+ With `ordered=True`, you get the same output as `concurrency=1`: same values, same order, same ordinary failures. Only the timing changes.
118
+
119
+ Cancellation is the exception: `CancelledError` starts teardown right away in either mode. Teardown still waits for the stage's tasks, though, so a task that swallows cancellation delays it either way.
120
+
121
+ Ordering has two trade-offs:
122
+
123
+ - **Failures wait their turn**: if item 1 is slow and item 2 fails, an ordered stage waits for item 1 before raising. An unordered stage cancels pending work right away.
124
+ - **Ordered `flat_map` holds more**: each running expansion gets its own buffer, so the stage can hold up to `concurrency * (buffer + 1)` values instead of `buffer + concurrency`. Because an endless expansion blocks everything behind it, only use ordered mode for finite expansions.
125
+
126
+ ## Error handling
127
+
128
+ **Pipelines fail fast.** When a stage raises, `flowlet` cancels pending work, runs cleanup, and re-raises.
129
+
130
+ To handle per-item failures without stopping the pipeline, catch them in your function and use `.flat_map(...)` to drop failed items:
131
+
132
+ ```python
133
+ async def safe_fetch(url: str) -> list[Page]:
134
+ try:
135
+ return [await fetch(url)]
136
+ except Exception:
137
+ return []
138
+
139
+
140
+ items = await pipe(urls).flat_map(safe_fetch, concurrency=20).collect()
141
+ ```
142
+
143
+ ## Blocking work
144
+
145
+ Blocking sync code stalls the event loop. Wrap blocking I/O in `in_thread` and CPU-bound work in `in_process`.
146
+
147
+ Either way, at most `min(concurrency, max_workers)` calls run at once. Cancelling the pipeline stops waiting for a submitted call, but it can't interrupt sync code that's already running in a worker thread or process.
148
+
149
+ ### Blocking I/O with `in_thread`
150
+
151
+ `in_thread(fn, *, executor=None)` runs `fn` in a thread pool and copies `contextvars` into the worker thread. With `executor=None`, it uses asyncio's default pool:
152
+
153
+ ```python
154
+ from flowlet import in_thread, pipe
155
+
156
+ items = await pipe(keys).map(in_thread(load_s3), concurrency=64).collect()
157
+ ```
158
+
159
+ Pass your own `ThreadPoolExecutor` to cap threads or share one pool across stages:
160
+
161
+ ```python
162
+ from concurrent.futures import ThreadPoolExecutor
163
+ from flowlet import in_thread, pipe
164
+
165
+ with ThreadPoolExecutor(max_workers=16) as pool:
166
+ items = await (
167
+ pipe(keys)
168
+ .map(in_thread(load_s3, executor=pool), concurrency=8)
169
+ .map(in_thread(parse_blob, executor=pool), concurrency=4)
170
+ .collect()
171
+ )
172
+ ```
173
+
174
+ With `flat_map(in_thread(fn))`, return a `list` or `tuple`, not a lazy generator. A generator gets created on the worker thread and iterated later on the event loop, which defeats the point.
175
+
176
+ ### Per-thread resources with `thread_local`
177
+
178
+ Use `@thread_local` to create a blocking client or session once per worker thread and reuse it on every later call in that thread. A plain function works if there's nothing to clean up. For cleanup, make it a generator: `flowlet` caches the first value it yields, and the `finally` block runs on `.close()` or when the thread exits.
179
+
180
+ To control when cleanup runs, manage the `ThreadPoolExecutor` with a `with` block. When the block exits, the worker threads shut down and their clients close:
181
+
182
+ ```python
183
+ from collections.abc import Generator
184
+ from concurrent.futures import ThreadPoolExecutor
185
+ from flowlet import in_thread, pipe, thread_local
186
+
187
+
188
+ @thread_local
189
+ def session() -> Generator[HttpClient]:
190
+ client = HttpClient()
191
+ try:
192
+ yield client
193
+ finally:
194
+ # Runs once per worker thread when the pool shuts down.
195
+ client.close()
196
+
197
+
198
+ def fetch(url: str) -> Page:
199
+ return session().get(url)
200
+
201
+
202
+ with ThreadPoolExecutor(max_workers=16) as pool:
203
+ pages = await (
204
+ pipe(urls)
205
+ .map(in_thread(fetch, executor=pool), concurrency=64)
206
+ .collect()
207
+ )
208
+ ```
209
+
210
+ A few details on lifetime:
211
+
212
+ - **Explicit close**: `session.close()` closes and clears only the calling thread's instance.
213
+ - **Cleanup errors**: exceptions on thread exit go to `sys.unraisablehook`, since there's no caller left to catch them.
214
+ - **Default pool**: resources created on asyncio's default pool stay open until the pool shuts down, which with `asyncio.run` is when the event loop closes.
215
+
216
+ ### CPU-bound work with `in_process`
217
+
218
+ `in_process(fn, *, executor)` runs CPU-bound work in a `ProcessPoolExecutor`. There's no default pool, so you create one and manage its lifetime:
219
+
220
+ ```python
221
+ from concurrent.futures import ProcessPoolExecutor
222
+ from flowlet import in_process, pipe
223
+
224
+ with ProcessPoolExecutor(max_workers=8) as pool:
225
+ items = await (
226
+ pipe(keys)
227
+ .map(in_process(crunch, executor=pool), concurrency=8)
228
+ .collect()
229
+ )
230
+ ```
231
+
232
+ A few process-pool rules apply:
233
+
234
+ - **Pickling**: the worker function, its arguments, and its return value must all be picklable. Define workers at module level rather than as lambdas or local functions.
235
+ - **Start methods**: Python 3.14 defaults to `forkserver` on Linux and `spawn` on macOS and Windows. Both re-import your main module, so put script entry points behind `if __name__ == "__main__":`.
236
+ - **No `contextvars`**: unlike `in_thread`, `in_process` doesn't copy `contextvars` to worker processes.
237
+
238
+ ## Reuse and other styles
239
+
240
+ ### Reusable fragments with `Flow`
241
+
242
+ A `Flow` is a pipeline without a source. Use it to name, test, and reuse a group of stages across different pipelines:
243
+
244
+ ```python
245
+ from flowlet import Flow, pipe
246
+
247
+ extract: Flow[Page, str] = (
248
+ Flow[Page]()
249
+ .flat_map(find_links)
250
+ .filter(is_internal)
251
+ .map(normalize_url)
252
+ )
253
+
254
+ links = await pipe(pages).through(extract).collect()
255
+ ```
256
+
257
+ You can also compose flows with `.through(...)`, or run one directly on a source with `extract.apply(pages)`.
258
+
259
+ For type checking, start with `Flow[T]()` so the input type flows through every stage (`Flow[T, U]` takes `T` and produces `U`). Bare `Flow()` works too, but starts as `Flow[Any, Any]`.
260
+
261
+ ### Pipe operator (`|`) with `op`
262
+
263
+ Each function in `flowlet.op` builds a one-step `Flow`, and `|` chains them. It runs the same as method chaining, and it's handy for naming a reusable fragment without writing `Flow[T]()`:
264
+
265
+ ```python
266
+ from flowlet import op, pipe
267
+
268
+ extract = (
269
+ op.flat_map(find_links)
270
+ | op.filter(is_internal)
271
+ | op.map(normalize_url)
272
+ )
273
+
274
+ links = await (pipe(pages) | extract).collect() # same as .through(extract)
275
+ ```
276
+
277
+ ### Functional API
278
+
279
+ `flowlet.functional` exposes the curried operators behind everything above. Compose them with `chain`:
280
+
281
+ ```python
282
+ import flowlet.functional as F
283
+
284
+ process = F.chain(
285
+ F.map(fetch, concurrency=20),
286
+ F.flat_map(extract_links),
287
+ F.filter(is_valid),
288
+ )
289
+
290
+ items = await F.collect(process(urls))
291
+ ```
292
+
293
+ You can also call any operator directly: `F.map(fetch, concurrency=20)(urls)` returns an `AsyncGenerator`.
@@ -0,0 +1,68 @@
1
+ [project]
2
+ name = "flowlet"
3
+ version = "0.5.0"
4
+ description = "A minimal async pipeline library"
5
+ readme = "README.md"
6
+ license = "BSD-3-Clause"
7
+ requires-python = ">=3.14"
8
+ dependencies = []
9
+
10
+ [build-system]
11
+ requires = ["uv_build>=0.9.26,<1.0.0"]
12
+ build-backend = "uv_build"
13
+
14
+ [tool.pytest.ini_options]
15
+ minversion = "6.0"
16
+ addopts = "-s"
17
+ asyncio_default_fixture_loop_scope = "function"
18
+
19
+ [tool.ruff.lint]
20
+ select = [
21
+ "A",
22
+ "E",
23
+ "F",
24
+ "I",
25
+ "U",
26
+ "YTT",
27
+ "B",
28
+ "C4",
29
+ "Q",
30
+ "SIM",
31
+ "ISC",
32
+ "ICN",
33
+ "W",
34
+ "RUF027",
35
+ ]
36
+ ignore = [
37
+ "E203",
38
+ "B028",
39
+ "B905",
40
+ "C408",
41
+ "SIM108",
42
+ "COM812",
43
+ ]
44
+ preview = true
45
+
46
+ [tool.ruff.format]
47
+ exclude = ["*.md"]
48
+
49
+ [tool.mypy]
50
+ python_version = "3.14"
51
+ ignore_missing_imports = true
52
+ check_untyped_defs = true
53
+ no_implicit_optional = true
54
+ warn_unreachable = true
55
+ warn_unused_ignores = true
56
+ warn_redundant_casts = true
57
+ strict_equality = true
58
+ extra_checks = true
59
+ allow_untyped_defs = false
60
+ allow_any_generics = false
61
+
62
+ [dependency-groups]
63
+ dev = [
64
+ "pytest>=9.2.0",
65
+ "pytest-asyncio>=1.5.0",
66
+ "mypy>=2.4.1",
67
+ "ruff>=0.17.6",
68
+ ]