From fe5eba9b31bb525f075edf046af8b3542db85e84 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 13 Sep 2023 15:36:07 -0500 Subject: [PATCH] Use cached_property in device registry (#100309) --- homeassistant/helpers/device_registry.py | 14 +++++--------- tests/syrupy.py | 1 - 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/homeassistant/helpers/device_registry.py b/homeassistant/helpers/device_registry.py index 64d102d020f..064579a95d3 100644 --- a/homeassistant/helpers/device_registry.py +++ b/homeassistant/helpers/device_registry.py @@ -12,6 +12,7 @@ from urllib.parse import urlparse import attr from yarl import URL +from homeassistant.backports.functools import cached_property from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError @@ -211,7 +212,7 @@ def _validate_configuration_url(value: Any) -> str | None: return str(value) -@attr.s(slots=True, frozen=True) +@attr.s(frozen=True) class DeviceEntry: """Device Registry Entry.""" @@ -234,8 +235,6 @@ class DeviceEntry: # This value is not stored, just used to keep track of events to fire. is_new: bool = attr.ib(default=False) - _json_repr: str | None = attr.ib(cmp=False, default=None, init=False, repr=False) - @property def disabled(self) -> bool: """Return if entry is disabled.""" @@ -262,15 +261,12 @@ class DeviceEntry: "via_device_id": self.via_device_id, } - @property + @cached_property def json_repr(self) -> str | None: """Return a cached JSON representation of the entry.""" - if self._json_repr is not None: - return self._json_repr - try: dict_repr = self.dict_repr - object.__setattr__(self, "_json_repr", JSON_DUMP(dict_repr)) + return JSON_DUMP(dict_repr) except (ValueError, TypeError): _LOGGER.error( "Unable to serialize entry %s to JSON. Bad data found at %s", @@ -279,7 +275,7 @@ class DeviceEntry: find_paths_unserializable_data(dict_repr, dump=JSON_DUMP) ), ) - return self._json_repr + return None @attr.s(slots=True, frozen=True) diff --git a/tests/syrupy.py b/tests/syrupy.py index 4846e013f5d..9209654a607 100644 --- a/tests/syrupy.py +++ b/tests/syrupy.py @@ -158,7 +158,6 @@ class HomeAssistantSnapshotSerializer(AmberDataSerializer): ) if serialized["via_device_id"] is not None: serialized["via_device_id"] = ANY - serialized.pop("_json_repr") return serialized @classmethod