Reduce code for registry items with a base class (#114689)
This commit is contained in:
parent
d17f308c6a
commit
adbaed2c6d
4 changed files with 89 additions and 88 deletions
|
@ -3,7 +3,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from collections import UserDict
|
||||
from collections.abc import ValuesView
|
||||
from typing import TYPE_CHECKING, Any, Literal, TypeVar
|
||||
|
||||
from homeassistant.core import CoreState, HomeAssistant, callback
|
||||
|
||||
|
@ -14,6 +16,54 @@ SAVE_DELAY = 10
|
|||
SAVE_DELAY_LONG = 180
|
||||
|
||||
|
||||
_DataT = TypeVar("_DataT")
|
||||
|
||||
|
||||
class BaseRegistryItems(UserDict[str, _DataT], ABC):
|
||||
"""Base class for registry items."""
|
||||
|
||||
data: dict[str, _DataT]
|
||||
|
||||
def values(self) -> ValuesView[_DataT]:
|
||||
"""Return the underlying values to avoid __iter__ overhead."""
|
||||
return self.data.values()
|
||||
|
||||
@abstractmethod
|
||||
def _index_entry(self, key: str, entry: _DataT) -> None:
|
||||
"""Index an entry."""
|
||||
|
||||
@abstractmethod
|
||||
def _unindex_entry(self, key: str, replacement_entry: _DataT | None = None) -> None:
|
||||
"""Unindex an entry."""
|
||||
|
||||
def __setitem__(self, key: str, entry: _DataT) -> None:
|
||||
"""Add an item."""
|
||||
data = self.data
|
||||
if key in data:
|
||||
self._unindex_entry(key, entry)
|
||||
data[key] = entry
|
||||
self._index_entry(key, entry)
|
||||
|
||||
def _unindex_entry_value(
|
||||
self, key: str, value: str, index: dict[str, dict[str, Literal[True]]]
|
||||
) -> None:
|
||||
"""Unindex an entry value.
|
||||
|
||||
key is the entry key
|
||||
value is the value to unindex such as config_entry_id or device_id.
|
||||
index is the index to unindex from.
|
||||
"""
|
||||
entries = index[value]
|
||||
del entries[key]
|
||||
if not entries:
|
||||
del index[value]
|
||||
|
||||
def __delitem__(self, key: str) -> None:
|
||||
"""Remove an item."""
|
||||
self._unindex_entry(key)
|
||||
super().__delitem__(key)
|
||||
|
||||
|
||||
class BaseRegistry(ABC):
|
||||
"""Class to implement a registry."""
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue