Add support for attribute caching to the event platform (#106330)

This commit is contained in:
J. Nick Koston 2023-12-23 13:23:32 -10:00 committed by GitHub
parent b674985b20
commit 6e6d7a0c92
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 4 deletions

View File

@ -5,7 +5,7 @@ from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from enum import StrEnum
import logging
from typing import Any, Self, final
from typing import TYPE_CHECKING, Any, Self, final
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
@ -21,6 +21,12 @@ from homeassistant.util import dt as dt_util
from .const import ATTR_EVENT_TYPE, ATTR_EVENT_TYPES, DOMAIN
if TYPE_CHECKING:
from functools import cached_property
else:
from homeassistant.backports.functools import cached_property
SCAN_INTERVAL = timedelta(seconds=30)
ENTITY_ID_FORMAT = DOMAIN + ".{}"
@ -101,7 +107,13 @@ class EventExtraStoredData(ExtraStoredData):
return None
class EventEntity(RestoreEntity):
CACHED_PROPERTIES_WITH_ATTR_ = {
"device_class",
"event_types",
}
class EventEntity(RestoreEntity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
"""Representation of an Event entity."""
_entity_component_unrecorded_attributes = frozenset({ATTR_EVENT_TYPES})
@ -115,7 +127,7 @@ class EventEntity(RestoreEntity):
__last_event_type: str | None = None
__last_event_attributes: dict[str, Any] | None = None
@property
@cached_property
def device_class(self) -> EventDeviceClass | None:
"""Return the class of this entity."""
if hasattr(self, "_attr_device_class"):
@ -124,7 +136,7 @@ class EventEntity(RestoreEntity):
return self.entity_description.device_class
return None
@property
@cached_property
def event_types(self) -> list[str]:
"""Return a list of possible events."""
if hasattr(self, "_attr_event_types"):

View File

@ -56,6 +56,9 @@ async def test_event() -> None:
event_types=["short_press", "long_press"],
device_class=EventDeviceClass.DOORBELL,
)
# Delete the cache since we changed the entity description
# at run time
del event.device_class
assert event.event_types == ["short_press", "long_press"]
assert event.device_class == EventDeviceClass.DOORBELL