Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
mdeweerd committed Jul 10, 2023
1 parent 85dd871 commit 9327508
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions custom_components/zha_toolkit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import re
import typing
from enum import Enum
from typing import Any

import packaging
import packaging.version
Expand Down Expand Up @@ -842,27 +841,59 @@ def extractParams( # noqa: C901
#
async def retry(
func: typing.Callable[[], typing.Awaitable[typing.Any]],
retry_exceptions: typing.Iterable[Any], # typing.Iterable[BaseException],
retry_exceptions: typing.Iterable[typing.Any]
| None = None, # typing.Iterable[BaseException],
tries: int = 3,
delay: int | float = 0.1,
) -> typing.Any:
"""Retry a function in case of exception
Only exceptions in `retry_exceptions` will be retried.
"""
if retry_exceptions is None:
# Default list
retry_exceptions = (
(
DeliveryError,
ControllerException,
asyncio.CancelledError,
asyncio.TimeoutError,
),
)

while True:
LOGGER.debug("Tries remaining: %s", tries)
try:
return await func()
# pylint: disable-next=catching-non-exception
except retry_exceptions: # type:ignore[misc]
if tries <= 1:
raise
tries -= 1
await asyncio.sleep(delay)


async def retry_wrapper(
func: typing.Callable,
*args,
retry_exceptions: typing.Iterable[typing.Any]
| None = None, # typing.Iterable[BaseException],
tries: int = 3,
delay: int | float = 0.1,
**kwargs,
) -> typing.Any:
"""Inline callable wrapper for retry"""
return await retry(
functools.partial(func, *args, **kwargs),
retry_exceptions,
tries=tries,
delay=delay,
)


def retryable(
retry_exceptions: typing.Iterable[Any], # typing.Iterable[BaseException]
retry_exceptions: None
| typing.Iterable[typing.Any] = None, # typing.Iterable[BaseException]
tries: int = 1,
delay: float = 0.1,
) -> typing.Callable:
Expand Down

0 comments on commit 9327508

Please sign in to comment.