4

I try to count time using %time in Jupyter-notebook, and some SyntaxError just makes me confused. Here is a simple code that can demonstrate the problem

import asyncio
async def main():
    print(1)
    
%time asyncio.run(main())

which throws RuntimeError: asyncio.run() cannot be called from a running event loop

according to asyncio.run() cannot be called from a running event loop, I change the code like this

import asyncio
async def main():
    print(1)
    
%time await main()

and it throws SyntaxError: 'await' outside function

when I remove the %time part the code works fine.

Did jupyter not support %time with asyncio functions?

leo liu
  • 47
  • 1
  • 4
  • Your first attempt would have worked in terminal IPython, but [not in a notebook kernel](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#using-autoawait-in-a-notebook-ipykernel). – user2357112 Dec 10 '20 at 09:25

1 Answers1

1

Unfortunately, ipython (therefore juypter) doesn't support magics interoperability with async.

https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#effects-on-magics

A couple of magics (%%timeit, %timeit, %%time, %%prun) have not yet been updated to work with asynchronous code and will raise syntax errors when trying to use top-level await. We welcome any contribution to help fix those, and extra cases we haven’t caught yet. We hope for better support in Core Python for top-level Async code.

thomas.han
  • 2,891
  • 2
  • 17
  • 14