[Python] Python. Attach data to asyncio.Task

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    Is there proper way to attach additional data to asyncio.create_task()? The example is

    import asyncio
    from dataclasses import dataclass


    @dataclass
    class Foo:
    name: str
    url_to_download: str
    size: int
    ...

    async def download_file(url: str):
    return await download_impl()

    objs: list[Foo] = [obj1, obj2, ...]

    # Question
    # How to attach the Foo object to the each task?
    tasks = [asyncio.create_task(download_file(obj.url_to_download)) for obj in objs]

    for task in asyncio.as_completed(tasks):
    # Question
    # How to find out which Foo obj corresponds the downloaded data?
    data = await task
    process(data)


    There is also way to forward the Foo object to the download_file and return it with the downloaded data, but it is poor design. Do I miss something, or anyone has a better design to solve that problem?

    Continue reading...

Compartilhe esta Página