Skip to content

Instantly share code, notes, and snippets.

@1st1
Created March 12, 2017 19:06
Show Gist options
  • Save 1st1/1cc67287654cc575ea41e8e623ea8c71 to your computer and use it in GitHub Desktop.
Save 1st1/1cc67287654cc575ea41e8e623ea8c71 to your computer and use it in GitHub Desktop.
Fixing await
import asyncio
import sys
def run(main):
def coro_wrapper(coro):
if not sys._getframe(1).f_inawait:
raise RuntimeError(
'creating a coroutine outside of await expression')
return coro
c = main()
old_wrapper = sys.get_coroutine_wrapper()
sys.set_coroutine_wrapper(coro_wrapper)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(c)
finally:
sys.set_coroutine_wrapper(old_wrapper)
loop.close()
async def baz():
print('hi')
async def bar():
await baz() # try removing "await"
async def foo():
await bar()
run(foo)
Traceback (most recent call last):
File "t.py", line 37, in <module>
run(foo)
File "t.py", line 19, in run
loop.run_until_complete(c)
File "/Users/yury/dev/py/cpython/Lib/asyncio/base_events.py", line 465, in run_until_complete
return future.result()
File "t.py", line 34, in foo
await bar()
File "t.py", line 30, in bar
baz() # try removing "await"
File "t.py", line 9, in coro_wrapper
'creating a coroutine outside of await expression')
RuntimeError: creating a coroutine outside of await expression
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment