await at the top of a notebook cell
In a Jupyter notebook you can write await directly in a cell, without async def or asyncio.run().
Used in 21 lessons of the course, from 01.05.
Normally await is only valid inside an async def function. Outside one, in a .py script, Python raises a SyntaxError.
Jupyter (through IPython) is different: it already has an event loop running behind every cell. So it accepts a bare await at the top level of a cell and waits for the result for you.
In the course you see it like this: print(await async_model.ainvoke("q1")). That line works in the notebook as it is. In a regular script you would put it inside an async def function and start it with asyncio.run().
The example below is a regular script, so it uses asyncio.run(). That is what Jupyter does for you invisibly.
# notebook: await coro()
# script: asyncio.run(coro())
Reach for it when: you work in a Jupyter notebook and want to call something async, like `ainvoke`, directly. In a script, use `asyncio.run()`.
Examples
Common mistake
async def ask():
return 1
print(await ask())Why: In a script, `await` outside an `async def` function is not valid. Only Jupyter allows it at the top level.
How to write it: Put the call inside an async def main() function and run it with asyncio.run(main()).
