Skip to content

Commit

Permalink
Add support for attribute caching to the text platform
Browse files Browse the repository at this point in the history
Builds on #100601
  • Loading branch information
bdraco committed Dec 22, 2023
1 parent 3a744d3 commit 49371a2
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions homeassistant/components/text/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from enum import StrEnum
import logging
import re
from typing import Any, final
from typing import TYPE_CHECKING, Any, final

import voluptuous as vol

Expand All @@ -33,6 +33,11 @@
SERVICE_SET_VALUE,
)

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 + ".{}"
Expand Down Expand Up @@ -107,7 +112,16 @@ class TextEntityDescription(EntityDescription, frozen_or_thawed=True):
pattern: str | None = None


class TextEntity(Entity):
CACHED_PROPERTIES_WITH_ATTR_ = {
"mode",
"native_value",
"native_min",
"native_max",
"pattern",
}


class TextEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
"""Representation of a Text entity."""

_entity_component_unrecorded_attributes = frozenset(
Expand Down Expand Up @@ -156,7 +170,7 @@ def state(self) -> str | None:
)
return self.native_value

@property
@cached_property
def mode(self) -> TextMode:
"""Return the mode of the entity."""
if hasattr(self, "_attr_mode"):
Expand All @@ -165,7 +179,7 @@ def mode(self) -> TextMode:
return self.entity_description.mode
return TextMode.TEXT

@property
@cached_property
def native_min(self) -> int:
"""Return the minimum length of the value."""
if hasattr(self, "_attr_native_min"):
Expand All @@ -180,7 +194,7 @@ def min(self) -> int:
"""Return the minimum length of the value."""
return max(self.native_min, 0)

@property
@cached_property
def native_max(self) -> int:
"""Return the maximum length of the value."""
if hasattr(self, "_attr_native_max"):
Expand All @@ -206,7 +220,7 @@ def pattern_cmp(self) -> re.Pattern | None:
self.__pattern_cmp = re.compile(self.pattern)
return self.__pattern_cmp

@property
@cached_property
def pattern(self) -> str | None:
"""Return the regex pattern that the value must match."""
if hasattr(self, "_attr_pattern"):
Expand All @@ -215,7 +229,7 @@ def pattern(self) -> str | None:
return self.entity_description.pattern
return None

@property
@cached_property
def native_value(self) -> str | None:
"""Return the value reported by the text."""
return self._attr_native_value
Expand Down

0 comments on commit 49371a2

Please sign in to comment.