Created
June 14, 2024 04:45
POC: wrapper for a function that can either run sychrnously or be awaited in an asyncio context:
This file contains 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
# here, the function that can work "either way" is the nested "payload". | |
# The external ^morphix_in_thread" can be a decorator, and "payload" the decorated function | |
def morphix_in_thread(): | |
try: | |
loop = asyncio.get_running_loop() | |
except RuntimeError: | |
loop = None | |
def payload(): | |
time.sleep(1.5) | |
return 5 | |
if not loop: | |
return payload() | |
f = asyncio.Future() | |
async def apayload(): | |
return await loop.run_in_executor(None, payload) | |
task = loop.create_task(apayload()) | |
task.add_done_callback(lambda t: f.set_result(t.result())) | |
return f | |
""" | |
In [97]: async def main(): | |
...: return await morphix_in_thread() | |
...: | |
In [98]: asyncio.run(main()) | |
Out[98]: 5 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment