Skip to content

Instantly share code, notes, and snippets.

@pquentin
Created September 8, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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