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:
Jan Bouwhuis 2024-03-17 21:23:46 +01:00 committed by GitHub
parent d8f74571a1
commit 685553d17d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Generator, Sequence
from collections.abc import Callable, Generator, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING
@ -10,6 +10,25 @@ if TYPE_CHECKING:
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):
"""General Home Assistant exception occurred."""
@ -52,10 +71,12 @@ class HomeAssistantError(Exception):
assert self.translation_key is not None
assert self.translation_domain is not None
# pylint: disable-next=import-outside-toplevel
from .helpers.translation import async_get_exception_message
if "async_get_exception_message" not in _function_cache:
_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
)
return self._message