Cache late imported async_get_exception_message for HomeAssistantError (#113683)
* Cache late imported async_get_exception_message for HomeAssistantError * Use a dict to store the function cache * Update homeassistant/exceptions.py Co-authored-by: J. Nick Koston <nick@koston.org> --------- Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
parent
d8f74571a1
commit
685553d17d
1 changed files with 25 additions and 4 deletions
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Generator, Sequence
|
from collections.abc import Callable, Generator, Sequence
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
@ -10,6 +10,25 @@ if TYPE_CHECKING:
|
||||||
from .core import Context
|
from .core import Context
|
||||||
|
|
||||||
|
|
||||||
|
_function_cache: dict[str, Callable[[str, str, dict[str, str] | None], str]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def import_async_get_exception_message() -> (
|
||||||
|
Callable[[str, str, dict[str, str] | None], str]
|
||||||
|
):
|
||||||
|
"""Return a method that can fetch a translated exception message.
|
||||||
|
|
||||||
|
Defaults to English, requires translations to already be cached.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable-next=import-outside-toplevel
|
||||||
|
from .helpers.translation import (
|
||||||
|
async_get_exception_message as async_get_exception_message_import,
|
||||||
|
)
|
||||||
|
|
||||||
|
return async_get_exception_message_import
|
||||||
|
|
||||||
|
|
||||||
class HomeAssistantError(Exception):
|
class HomeAssistantError(Exception):
|
||||||
"""General Home Assistant exception occurred."""
|
"""General Home Assistant exception occurred."""
|
||||||
|
|
||||||
|
@ -52,10 +71,12 @@ class HomeAssistantError(Exception):
|
||||||
assert self.translation_key is not None
|
assert self.translation_key is not None
|
||||||
assert self.translation_domain is not None
|
assert self.translation_domain is not None
|
||||||
|
|
||||||
# pylint: disable-next=import-outside-toplevel
|
if "async_get_exception_message" not in _function_cache:
|
||||||
from .helpers.translation import async_get_exception_message
|
_function_cache[
|
||||||
|
"async_get_exception_message"
|
||||||
|
] = import_async_get_exception_message()
|
||||||
|
|
||||||
self._message = async_get_exception_message(
|
self._message = _function_cache["async_get_exception_message"](
|
||||||
self.translation_domain, self.translation_key, self.translation_placeholders
|
self.translation_domain, self.translation_key, self.translation_placeholders
|
||||||
)
|
)
|
||||||
return self._message
|
return self._message
|
||||||
|
|
Loading…
Add table
Reference in a new issue