Skip to content

Instantly share code, notes, and snippets.

@pquentin
Created September 8, 2023 06:26
Show Gist options
  • Save pquentin/935c3d70e33660cd267c039c646f69d8 to your computer and use it in GitHub Desktop.
Save pquentin/935c3d70e33660cd267c039c646f69d8 to your computer and use it in GitHub Desktop.
Experimenting with run_secretly_sync_async_fn
import trio
class SyncBackend:
def return_2(self):
return 2
class AsyncBackend:
async def return_2(self):
return 2
async def work(backend):
print(await backend.return_2())
# async usage, works as expected
trio.run(work, AsyncBackend())
# adapted from https://github.com/python-trio/hip/issues/1#issuecomment-322028457
def run_secretly_sync_async_fn(async_fn, *args, **kwargs):
coro = async_fn(*args, **kwargs)
try:
coro.send(None)
except StopIteration as exc:
return exc.value
else:
raise RuntimeError("you lied, this async function is not secretly synchronous")
# sync usage, fails with TypeError: object int can't be used in 'await' expression
run_secretly_sync_async_fn(work, backend=SyncBackend())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment