[Python] How to use an async for loop to iterate over a list?

Discussão em 'Python' iniciado por Stack, Agosto 24, 2025.

  1. Stack

    Stack Membro Participativo

    So I need to call an async function for all items in a list. This could be a list of URLs and an async function using aiohttp that gets a response back from every URL. Now obviously I cannot do the following:

    async for url in ['www.google.com', 'www.youtube.com', 'www.aol.com']:


    I can use a normal for loop but then my code will act synchronously and I lose the benefits and speed of having an async response fetching function.

    Is there any way I can convert a list such that the above works? I just need to change the list's __iter__() to a __aiter__() method right? Can this be achieved by subclassing a list? Maybe encapsulating it in a class?

    Continue reading...

Compartilhe esta Página