From 685553d17d55cfa1ee9406f8aa454a355f37022b Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Sun, 17 Mar 2024 21:23:46 +0100 Subject: [PATCH] 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 --------- Co-authored-by: J. Nick Koston --- homeassistant/exceptions.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/homeassistant/exceptions.py b/homeassistant/exceptions.py index 409fa3450bd..b9e1ca2e2bd 100644 --- a/homeassistant/exceptions.py +++ b/homeassistant/exceptions.py @@ -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