Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Forked from konpatp/async.py
Last active November 23, 2022 01:04
Show Gist options
  • Select an option

  • Save wonderbeyond/f2eb849d1e5f024a88508b60db376b49 to your computer and use it in GitHub Desktop.

Select an option

Save wonderbeyond/f2eb849d1e5f024a88508b60db376b49 to your computer and use it in GitHub Desktop.
Python turn sync functions to async (and async to sync)
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
@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