From a5cde8a61e432687a6206ed5f49272bafab800c7 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Sat, 16 Mar 2024 05:01:46 +0100 Subject: [PATCH] Improve typing of State.as_compressed_state (#113540) --- homeassistant/const.py | 10 +++++----- homeassistant/core.py | 27 ++++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 04561f489dd..28409ba0907 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -1456,11 +1456,11 @@ _DEPRECATED_DATA_RATE_GIBIBYTES_PER_SECOND: Final = DeprecatedConstantEnum( # States -COMPRESSED_STATE_STATE = "s" -COMPRESSED_STATE_ATTRIBUTES = "a" -COMPRESSED_STATE_CONTEXT = "c" -COMPRESSED_STATE_LAST_CHANGED = "lc" -COMPRESSED_STATE_LAST_UPDATED = "lu" +COMPRESSED_STATE_STATE: Final = "s" +COMPRESSED_STATE_ATTRIBUTES: Final = "a" +COMPRESSED_STATE_CONTEXT: Final = "c" +COMPRESSED_STATE_LAST_CHANGED: Final = "lc" +COMPRESSED_STATE_LAST_UPDATED: Final = "lu" # #### SERVICES #### SERVICE_TURN_ON: Final = "turn_on" diff --git a/homeassistant/core.py b/homeassistant/core.py index 7f10d8f6df5..a6262c56c81 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -31,7 +31,18 @@ import re import threading import time from time import monotonic -from typing import TYPE_CHECKING, Any, Generic, Literal, ParamSpec, Self, cast, overload +from typing import ( + TYPE_CHECKING, + Any, + Generic, + Literal, + NotRequired, + ParamSpec, + Self, + TypedDict, + cast, + overload, +) from urllib.parse import urlparse from typing_extensions import TypeVar @@ -1534,6 +1545,16 @@ class EventBus: ) +class CompressedState(TypedDict): + """Compressed dict of a state.""" + + s: str # COMPRESSED_STATE_STATE + a: ReadOnlyDict[str, Any] # COMPRESSED_STATE_ATTRIBUTES + c: str | dict[str, Any] # COMPRESSED_STATE_CONTEXT + lc: float # COMPRESSED_STATE_LAST_CHANGED + lu: NotRequired[float] # COMPRESSED_STATE_LAST_UPDATED + + class State: """Object to represent a state within the state machine. @@ -1663,7 +1684,7 @@ class State: return json_fragment(self.as_dict_json) @cached_property - def as_compressed_state(self) -> dict[str, Any]: + def as_compressed_state(self) -> CompressedState: """Build a compressed dict of a state for adds. Omits the lu (last_updated) if it matches (lc) last_changed. @@ -1678,7 +1699,7 @@ class State: # to avoid callers outside of this module # from misusing it by mistake. context = state_context._as_dict # pylint: disable=protected-access - compressed_state = { + compressed_state: CompressedState = { COMPRESSED_STATE_STATE: self.state, COMPRESSED_STATE_ATTRIBUTES: self.attributes, COMPRESSED_STATE_CONTEXT: context,