Running Async Code
Monty can execute async Python code using therun_monty_async() helper function:
Async External Functions
You can provide async external functions that will be awaited automatically:- Python
- JavaScript
run_monty_async() automatically handles both sync and async external functions. Sync functions are called directly, while async functions are awaited.Mixed Sync and Async Functions
You can mix sync and async external functions in the same execution:Asyncio.gather for Concurrent Execution
Monty supportsasyncio.gather() for running multiple async operations concurrently:
Complex Async Patterns
Monty handles nestedasyncio.gather() with external functions:
Manual Async Handling with FutureSnapshot
For advanced use cases, you can manually handle async execution usingFutureSnapshot:
Multiple Pending Futures
Most users should use
run_monty_async() instead of manually handling FutureSnapshot. Manual handling is only needed for advanced patterns like custom async schedulers.Async with OS Access
run_monty_async() supports OS access for file operations:
Error Handling in Async Code
Exceptions from async external functions propagate normally:Exception Handling in Async Code
Async exceptions can be caught with try/except:JavaScript Async Example
Performance Considerations
1
Use asyncio.gather for concurrency
When you need to call multiple external functions, use
asyncio.gather() to run them concurrently instead of sequentially:2
Prefer async for I/O
Use async external functions for I/O-bound operations (network, file, database):
3
Keep sync for CPU-bound work
Use sync functions for CPU-bound operations that don’t benefit from async:
Best Practices
- Use
run_monty_async()for simplicity: It handles both sync and async functions automatically - Provide type stubs for async functions: Help type checking understand async function signatures
- Handle exceptions properly: Async exceptions propagate the same way as sync exceptions
- Use
asyncio.gather()wisely: Only for independent operations that can run concurrently - Test error paths: Make sure your error handling works for both sync and async paths
When to Use Async
Use async execution when:- Your external functions perform I/O (network requests, file operations, database queries)
- You need to call multiple external functions concurrently
- You’re building a web service or API that uses async frameworks (FastAPI, aiohttp)
- Your code has no external function calls
- External functions are CPU-bound (computation, parsing)
- You’re building a simple script or tool
Next Steps
Iterative Execution
Learn about manual async handling with FutureSnapshot
Error Handling
Handle exceptions in async code
