Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%time await main() throws SyntaxError: 'await' outside function in jupyter

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?

like image 731
leo liu Avatar asked Oct 29 '25 04:10

leo liu


1 Answers

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.

like image 189
thomas.han Avatar answered Oct 30 '25 17:10

thomas.han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!