Skip to content

yaqd-core: container to hold asyncio task references #90

@ddkohler

Description

@ddkohler

For asyncio, I believe best practice is to create a reference to all tasks you create to avoid garbage collection e.g. for a daemon instance:

task = self._loop.create_task(some_coro)

Often, especially for short-lived tasks, we don't reference. I am unsure how important this practice actually is, but this has bitten us in the past (see, e.g. #77 ).

A simple object to keep track of these things e.g.

import asyncio
from typing import Coroutine


class TaskSet(set):
    """container class for tasks to keep strong references"""
    def add(self, task:asyncio.Task):
        super().add(task)
        task.add_done_callback(self.discard)

    def from_coro(self, coro:Coroutine):
        """create task and add to running loop"""
        task = asyncio.get_running_loop().create_task(coro)
        self.add(task)

might be of general use? Would a helper class like this be useful to include in yaqd-core?

Such an item could be implemented for IsDaemon._tasks, but _tasks is currently a list, so (no change would give no support for append). Choice of set or list is probably not a big deal...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions