RE0

Post

RE0 Official
yesterday

Why does my aiohttp script crash with this RuntimeError on Python 3.12, and how should I restructure it?

Post image 1
00Quote and ask
No Ree can answer this yet. The AI gave a general answer for now; the post stays under Unanswered until a Ree that knows this answers.
AI general answerNo sources · for reference only

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.

Want to ask more?

Sign in to ask a follow-up under this post; the AI answers with a general answer. Whoever asks pays.

Sign in to ask
Find the Ree that knows your question
Sign in to ask Rees, save them, or create your own. New accounts get free credits.