Skip to content

Commit

Permalink
fix: once handlers having same context
Browse files Browse the repository at this point in the history
once handlers had same `has_run` var, and once one run, none of the handlers wouldn't run ever again.
  • Loading branch information
jykob committed Dec 21, 2024
1 parent 37836b4 commit b9c0e6f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 26 deletions.
9 changes: 6 additions & 3 deletions tsbot/events/event_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

from typing_extensions import override

from tsbot import utils

if TYPE_CHECKING:
from tsbot import bot, events

Expand All @@ -29,9 +27,14 @@ async def run(self, bot: bot.TSBot, event: events.TSEvent) -> None:
@dataclass(slots=True)
class TSEventOnceHandler(TSEventHandler):
remove_event_handler_func: Callable[[TSEventHandler], None]
_has_run: bool = False

@override
@utils.async_run_once
async def run(self, bot: bot.TSBot, event: events.TSEvent) -> None:
if self._has_run:
return

self._has_run = True
self.remove_event_handler_func(self)

await self.handler(bot, event.ctx)
24 changes: 1 addition & 23 deletions tsbot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@

import asyncio
import contextlib
import functools
import logging
import time
from collections.abc import AsyncGenerator, Callable, Coroutine, Generator
from typing import ParamSpec, TypeVar

P = ParamSpec("P")
R = TypeVar("R")
from collections.abc import AsyncGenerator, Generator


@contextlib.asynccontextmanager
Expand All @@ -33,20 +28,3 @@ def set_event(event: asyncio.Event) -> Generator[None, None, None]:
yield
finally:
event.clear()


def async_run_once(
func: Callable[P, Coroutine[None, None, R]],
) -> Callable[P, Coroutine[None, None, R | None]]:
has_run = False

@functools.wraps(func)
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
nonlocal has_run
if has_run:
return None

has_run = True
return await func(*args, **kwargs)

return wrapper

0 comments on commit b9c0e6f

Please sign in to comment.