aiohttp ClientSession.get() async contextmanager work unexpected

Viewed 23
import asyncio

from aiohttp import ClientSession


async def download(session: ClientSession, link: str):
    print("init")
    async with session.get(link) as resp:
        print("hello")
        data = await resp.content.read()
        print("bye")
    return


async def amain():
    link = "https://www.google.com/"
    async with ClientSession() as session:
        tasks = []
        for _ in range(100_000):
            tasks.append(asyncio.create_task(download(session, link)))
            await asyncio.sleep(0) # <------------ Label 1
        await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(amain())

If u comment "Label 1" line, u got unexpected output like:

init
init
...
...
init

and then mixed 'hello' and 'bye' as expected.

but if that line uncommented we got 'init' 'hello' 'bye' mixed as u expected from async tasks.

Can anybody explain me, why async with session.get(link) as resp: block task until all tasks created, if they created without await asyncio.sleep(0)?

↓↓↓ works unexpected too:

async def amain():
    link = "https://www.google.com/"
    async with ClientSession() as session:
        await asyncio.gather(*(download(session, link) for _ in range(100_000)))
0 Answers
Related