async_manager¶
Async task management with multiprocessing workers and asyncio event loops.
This module provides: - AsyncContext: Manages multiple async context managers - AsyncManager: Pool of worker processes running asyncio event loops - AsyncRunner: Single-threaded asyncio event loop in a background thread - run_async(): Convenience function to submit coroutines to the global runner
Example
import concurrent.futures
import py_misc_utils.async_manager as am
async def add(a, b):
return a + b
fut = am.run_async(add(2, 3))
assert isinstance(fut, concurrent.futures.Future)
assert fut.result(timeout=5.0) == 5
AsyncContext
¶
Manages multiple async context managers with shared lifecycle.
Allows adding, removing, and getting context managers by name. Automatically enters/exits all contexts on close. get() enters a context only the first time it is requested - later calls with the same name return the same aenter() result.
Source code in py_misc_utils/async_manager.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
add(name, context)
async
¶
Add and enter a context manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Unique name for the context. |
required | |
context
|
Async context manager instance. |
required |
Returns:
| Type | Description |
|---|---|
|
Result of context.aenter(). |
Source code in py_misc_utils/async_manager.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
remove(name)
async
¶
Remove and exit a context manager by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Name of the context to remove. |
required |
Source code in py_misc_utils/async_manager.py
64 65 66 67 68 69 70 71 | |
get(name, context_ctor)
async
¶
Get or create a context manager by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Name of the context. |
required | |
context_ctor
|
Callable returning a new async context manager instance. |
required |
Returns:
| Type | Description |
|---|---|
|
Result of context.aenter() for the context. |
Source code in py_misc_utils/async_manager.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
close(*exc)
async
¶
Exit all managed contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*exc
|
Exception info to pass to aexit (type, value, traceback). |
()
|
Raises:
| Type | Description |
|---|---|
Exception
|
If any context's aexit returns False and an exception was being handled. |
Source code in py_misc_utils/async_manager.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
AsyncManager
¶
Pool of worker processes for parallel async task execution.
Distributes work across workers using a simple least-loaded strategy. Each worker runs an independent asyncio event loop in its own process. Each worker shares one AsyncContext, so context managers created via context.get(name, ctor) live as long as the worker - not per work item.
NOTE: work ctors must be picklable (module-level callables) since they travel through a multiprocessing queue to the worker processes.
Example
class Ctx:
async def __aenter__(self):
return 'ctx-value'
async def __aexit__(self, *exc):
return False
def make_ctx():
return Ctx()
async def work(context):
ctx = await context.get('res', make_ctx)
return (ctx, 21 * 2)
m = am.AsyncManager(num_workers=2)
m.enqueue_work('w1', work)
wid, res = m.fetch_result(block=True, timeout=5.0)
assert wid == 'w1' and res == ('ctx-value', 42)
m.close()
Source code in py_misc_utils/async_manager.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
close()
¶
Stop all worker processes.
Source code in py_misc_utils/async_manager.py
258 259 260 261 | |
enqueue_work(work_id, work_ctor)
¶
Submit work to the least-loaded worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
work_id
|
Unique identifier for the work item. |
required | |
work_ctor
|
Callable accepting 'context' kwarg, returning awaitable. |
required |
Source code in py_misc_utils/async_manager.py
263 264 265 266 267 268 269 270 271 272 273 274 275 | |
fetch_result(block=True, timeout=None)
¶
Fetch a completed work result.
Results of failed work items carry a WorkException instance - raised work errors do not terminate the fetch loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
Whether to block until a result is available (default: True). |
True
|
|
timeout
|
Maximum time to wait in seconds (default: None). |
None
|
Returns:
| Type | Description |
|---|---|
|
Tuple of (work_id, result) or None if timeout and non-blocking. |
Raises:
| Type | Description |
|---|---|
Empty
|
If block=False and no result available. |
Source code in py_misc_utils/async_manager.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
AsyncRunner
¶
Single-threaded asyncio event loop running in a background thread.
Provides a way to run async coroutines from synchronous code. Automatically registers for cleanup on process exit.
Example
import py_misc_utils.async_manager as am
runner = am.AsyncRunner()
async def sq(x):
return x * x
futs = [runner.run(sq(i)) for i in range(4)]
assert [f.result(timeout=5.0) for f in futs] == [0, 1, 4, 9]
runner.stop()
Source code in py_misc_utils/async_manager.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
stop()
¶
Stop the event loop and join the thread.
Source code in py_misc_utils/async_manager.py
345 346 347 348 | |
run(coro)
¶
Submit a coroutine to the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coro
|
Coroutine to execute. |
required |
Returns:
| Type | Description |
|---|---|
|
concurrent.futures.Future for the coroutine result. |
Source code in py_misc_utils/async_manager.py
350 351 352 353 354 355 356 357 358 359 | |
run_async(coro)
¶
Submit a coroutine to the global async runner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coro
|
Coroutine to execute. |
required |
Returns:
| Type | Description |
|---|---|
|
concurrent.futures.Future for the coroutine result. |
Source code in py_misc_utils/async_manager.py
372 373 374 375 376 377 378 379 380 381 | |