ipython icon indicating copy to clipboard operation
ipython copied to clipboard

Documentation for autoawait gives example that doesn't work

Open brianm78 opened this issue 9 months ago • 2 comments

The documentation for autoawait (ie. allowing automatic use of an event loop) at https://ipython.readthedocs.io/en/stable/interactive/autoawait.html gives some examples like:

In [1]: import aiohttp
   ...: session = aiohttp.ClientSession()
   ...: result = session.get('https://api.github.com')

In [2]: response = await result

However, this doesn't actually work as written - the first block will raise RuntimeError: no running event loop.

I think this is because no event loop is created unless the code being run actually contains an await instruction or similar, so code that requires the event loop to be running, but doesn't itself await will fail. Eg. modifying the above to include the response = await result in the same block as the setup logic does work.

Ideally there'd be a way to handle code like this - I'm not sure if always running an event loop (possibly configurable) has problems. If not, I think at least the examples should be amended to mention this.

brianm78 avatar Apr 06 '25 20:04 brianm78

Feel free to send a PR,

the easier way to force a loop is to await a dummy thing, like

from asynio import slepp
await sleep(0)

Yes this is a know limitation.

Carreau avatar Apr 08 '25 09:04 Carreau

The event loop is not being created even after running your snippet of code:

from asyncio import sleep, get_running_loop
await sleep(0)
get_running_loop() # RuntimeError: no running event loop

UPD: IPython 9.4.0, Python 3.13.5

mallo-c avatar Aug 06 '25 09:08 mallo-c