-
-
Save wonderbeyond/f2eb849d1e5f024a88508b60db376b49 to your computer and use it in GitHub Desktop.
Python turn sync functions to async (and async to sync)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| def force_async(fn): | |
| ''' | |
| turns a sync function to async function using threads | |
| ''' | |
| from concurrent.futures import ThreadPoolExecutor | |
| import asyncio | |
| pool = ThreadPoolExecutor() | |
| @functools.wraps(fn) | |
| def wrapper(*args, **kwargs): | |
| future = pool.submit(fn, *args, **kwargs) | |
| return asyncio.wrap_future(future) # make it awaitable | |
| return wrapper | |
| def force_sync(fn): | |
| ''' | |
| turn an async function to sync function | |
| ''' | |
| import asyncio | |
| @functools.wraps(fn) | |
| def wrapper(*args, **kwargs): | |
| res = fn(*args, **kwargs) | |
| if asyncio.iscoroutine(res): | |
| return asyncio.get_event_loop().run_until_complete(res) | |
| return res | |
| return wrapper |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @force_async | |
| def long_blocking_function(): | |
| import time | |
| time.sleep(10) | |
| return True | |
| import asyncio | |
| async def run(): | |
| a = long_blocking_function() | |
| b = long_blocking_function() | |
| return await asyncio.gather(a, b) # [True, True] in 10 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment