Async helpers
provide.foundation.utils.async_helpers
¶
Async-sync bridge utilities for Foundation.
Provides utilities for bridging async and sync code, particularly useful for CLI commands that need to call async clients or functions.
Functions¶
run_async
¶
Run an async coroutine from sync context.
IMPORTANT CONSTRAINTS:
This is a bridge utility for running async code from sync contexts (e.g., CLI commands).
It should NOT be used in async contexts - use await directly instead.
When to use: - CLI commands that need to call async client methods - Sync utility functions that need to call async APIs - Test fixtures that need to run async code synchronously
When NOT to use:
- Inside async functions (use await instead)
- In performance-critical loops (creates event loop overhead)
- With long-running coroutines (blocks the thread)
Limitations: - Creates a new event loop if one doesn't exist (has overhead) - Blocks the calling thread until coroutine completes - Cannot run multiple coroutines concurrently - Should not be nested (will raise RuntimeError)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coro
|
Coroutine[None, None, T] | Awaitable[T]
|
Async coroutine or awaitable to run |
required |
warn
|
bool
|
If True, logs a warning when used (for debugging) |
False
|
Returns:
| Type | Description |
|---|---|
T
|
Result from the coroutine |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called from within an already-running event loop |
Example
from provide.foundation.utils.async_helpers import run_async
async def fetch_data():
client = UniversalClient()
return await client.get("https://api.example.com/data")
result = run_async(fetch_data())
# ❌ BAD: Inside an async function
async def my_async_function():
result = run_async(some_coro()) # Wrong! Use await instead
Note
Consider refactoring to use native async entry points instead of bridging sync/async boundaries. This function is a convenience for specific use cases, not a general-purpose async executor.
Source code in provide/foundation/utils/async_helpers.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 120 121 122 123 124 | |