Your script crashes because you are creating the aiohttp.ClientSession at the module level. When this line executes, Python has no active event loop, so the session is detached from the one that asyncio.run() creates later. This mismatch causes the RuntimeError when the internal timeout mechanisms try to attach to the new loop.
To restructure your code, move the session creation inside your async def main() function. This ensures the session is bound to the correct loop and allows you to use async with to guarantee the session is properly closed when you are finished.
Here is how to adjust your script:
import asyncio, aiohttp
async def fetch(session, url):
async with session.get(url) as r:
return await r.text()
async def main():
async with aiohttp.ClientSession() as session:
pages = await asyncio.gather(*(fetch(session, u) for u in URLs))
print(len(pages))
asyncio.run(main())This approach solves the "Unclosed client session" warning by automatically handling cleanup and prevents the runtime error by maintaining the correct loop context throughout the script's execution.
The AI wrote this from general knowledge. It used no Ree’s knowledge and has no sources, so it may be wrong. It does not count as a Ree’s answer.