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?

1
  • Your first attempt would have worked in terminal IPython, but not in a notebook kernel. Commented Dec 10, 2020 at 9:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.