mirror of
https://github.com/home-assistant/core.git
synced 2025-07-19 19:27:45 +00:00
Use PEP 695 for class annotations (4) (#117778)
This commit is contained in:
parent
eedce95bc9
commit
8f0fb4db3e
@ -4,7 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from collections.abc import Awaitable, Callable
|
from collections.abc import Awaitable, Callable
|
||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
|
|
||||||
from homeassistant import config_entries
|
from homeassistant import config_entries
|
||||||
from homeassistant.components import onboarding
|
from homeassistant.components import onboarding
|
||||||
@ -22,13 +22,12 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
from .service_info.mqtt import MqttServiceInfo
|
from .service_info.mqtt import MqttServiceInfo
|
||||||
|
|
||||||
_R = TypeVar("_R", bound="Awaitable[bool] | bool")
|
type DiscoveryFunctionType[_R] = Callable[[HomeAssistant], _R]
|
||||||
DiscoveryFunctionType = Callable[[HomeAssistant], _R]
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class DiscoveryFlowHandler(config_entries.ConfigFlow, Generic[_R]):
|
class DiscoveryFlowHandler[_R: Awaitable[bool] | bool](config_entries.ConfigFlow):
|
||||||
"""Handle a discovery config flow."""
|
"""Handle a discovery config flow."""
|
||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
@ -7,7 +7,7 @@ from enum import StrEnum
|
|||||||
from functools import cached_property, lru_cache, partial
|
from functools import cached_property, lru_cache, partial
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
from typing import TYPE_CHECKING, Any, Literal, TypedDict, TypeVar
|
from typing import TYPE_CHECKING, Any, Literal, TypedDict
|
||||||
|
|
||||||
import attr
|
import attr
|
||||||
from yarl import URL
|
from yarl import URL
|
||||||
@ -449,10 +449,9 @@ class DeviceRegistryStore(storage.Store[dict[str, list[dict[str, Any]]]]):
|
|||||||
return old_data
|
return old_data
|
||||||
|
|
||||||
|
|
||||||
_EntryTypeT = TypeVar("_EntryTypeT", DeviceEntry, DeletedDeviceEntry)
|
class DeviceRegistryItems[_EntryTypeT: (DeviceEntry, DeletedDeviceEntry)](
|
||||||
|
BaseRegistryItems[_EntryTypeT]
|
||||||
|
):
|
||||||
class DeviceRegistryItems(BaseRegistryItems[_EntryTypeT]):
|
|
||||||
"""Container for device registry items, maps device id -> entry.
|
"""Container for device registry items, maps device id -> entry.
|
||||||
|
|
||||||
Maintains two additional indexes:
|
Maintains two additional indexes:
|
||||||
|
@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from typing import TypeVar
|
|
||||||
|
|
||||||
from .registry import BaseRegistryItems
|
from .registry import BaseRegistryItems
|
||||||
|
|
||||||
@ -15,16 +14,15 @@ class NormalizedNameBaseRegistryEntry:
|
|||||||
normalized_name: str
|
normalized_name: str
|
||||||
|
|
||||||
|
|
||||||
_VT = TypeVar("_VT", bound=NormalizedNameBaseRegistryEntry)
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1024)
|
@lru_cache(maxsize=1024)
|
||||||
def normalize_name(name: str) -> str:
|
def normalize_name(name: str) -> str:
|
||||||
"""Normalize a name by removing whitespace and case folding."""
|
"""Normalize a name by removing whitespace and case folding."""
|
||||||
return name.casefold().replace(" ", "")
|
return name.casefold().replace(" ", "")
|
||||||
|
|
||||||
|
|
||||||
class NormalizedNameBaseRegistryItems(BaseRegistryItems[_VT]):
|
class NormalizedNameBaseRegistryItems[_VT: NormalizedNameBaseRegistryEntry](
|
||||||
|
BaseRegistryItems[_VT]
|
||||||
|
):
|
||||||
"""Base container for normalized name registry items, maps key -> entry.
|
"""Base container for normalized name registry items, maps key -> entry.
|
||||||
|
|
||||||
Maintains an additional index:
|
Maintains an additional index:
|
||||||
|
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from collections import UserDict
|
from collections import UserDict
|
||||||
from collections.abc import Mapping, Sequence, ValuesView
|
from collections.abc import Mapping, Sequence, ValuesView
|
||||||
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
|
from typing import TYPE_CHECKING, Any, Literal
|
||||||
|
|
||||||
from homeassistant.core import CoreState, HomeAssistant, callback
|
from homeassistant.core import CoreState, HomeAssistant, callback
|
||||||
|
|
||||||
@ -16,11 +16,7 @@ SAVE_DELAY = 10
|
|||||||
SAVE_DELAY_LONG = 180
|
SAVE_DELAY_LONG = 180
|
||||||
|
|
||||||
|
|
||||||
_DataT = TypeVar("_DataT")
|
class BaseRegistryItems[_DataT](UserDict[str, _DataT], ABC):
|
||||||
_StoreDataT = TypeVar("_StoreDataT", bound=Mapping[str, Any] | Sequence[Any])
|
|
||||||
|
|
||||||
|
|
||||||
class BaseRegistryItems(UserDict[str, _DataT], ABC):
|
|
||||||
"""Base class for registry items."""
|
"""Base class for registry items."""
|
||||||
|
|
||||||
data: dict[str, _DataT]
|
data: dict[str, _DataT]
|
||||||
@ -65,7 +61,7 @@ class BaseRegistryItems(UserDict[str, _DataT], ABC):
|
|||||||
super().__delitem__(key)
|
super().__delitem__(key)
|
||||||
|
|
||||||
|
|
||||||
class BaseRegistry(ABC, Generic[_StoreDataT]):
|
class BaseRegistry[_StoreDataT: Mapping[str, Any] | Sequence[Any]](ABC):
|
||||||
"""Class to implement a registry."""
|
"""Class to implement a registry."""
|
||||||
|
|
||||||
hass: HomeAssistant
|
hass: HomeAssistant
|
||||||
|
@ -6,7 +6,7 @@ from collections.abc import Callable, Mapping, Sequence
|
|||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from functools import cache
|
from functools import cache
|
||||||
import importlib
|
import importlib
|
||||||
from typing import Any, Generic, Literal, Required, TypedDict, TypeVar, cast
|
from typing import Any, Literal, Required, TypedDict, cast
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
@ -21,8 +21,6 @@ from . import config_validation as cv
|
|||||||
|
|
||||||
SELECTORS: decorator.Registry[str, type[Selector]] = decorator.Registry()
|
SELECTORS: decorator.Registry[str, type[Selector]] = decorator.Registry()
|
||||||
|
|
||||||
_T = TypeVar("_T", bound=Mapping[str, Any])
|
|
||||||
|
|
||||||
|
|
||||||
def _get_selector_class(config: Any) -> type[Selector]:
|
def _get_selector_class(config: Any) -> type[Selector]:
|
||||||
"""Get selector class type."""
|
"""Get selector class type."""
|
||||||
@ -62,7 +60,7 @@ def validate_selector(config: Any) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class Selector(Generic[_T]):
|
class Selector[_T: Mapping[str, Any]]:
|
||||||
"""Base class for selectors."""
|
"""Base class for selectors."""
|
||||||
|
|
||||||
CONFIG_SCHEMA: Callable
|
CONFIG_SCHEMA: Callable
|
||||||
|
@ -9,7 +9,7 @@ from enum import Enum
|
|||||||
from functools import cache, partial
|
from functools import cache, partial
|
||||||
import logging
|
import logging
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
from typing import TYPE_CHECKING, Any, Generic, TypedDict, TypeGuard, TypeVar, cast
|
from typing import TYPE_CHECKING, Any, TypedDict, TypeGuard, cast
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
@ -79,8 +79,6 @@ ALL_SERVICE_DESCRIPTIONS_CACHE: HassKey[
|
|||||||
tuple[set[tuple[str, str]], dict[str, dict[str, Any]]]
|
tuple[set[tuple[str, str]], dict[str, dict[str, Any]]]
|
||||||
] = HassKey("all_service_descriptions_cache")
|
] = HassKey("all_service_descriptions_cache")
|
||||||
|
|
||||||
_T = TypeVar("_T")
|
|
||||||
|
|
||||||
|
|
||||||
@cache
|
@cache
|
||||||
def _base_components() -> dict[str, ModuleType]:
|
def _base_components() -> dict[str, ModuleType]:
|
||||||
@ -1153,7 +1151,7 @@ def verify_domain_control(
|
|||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
class ReloadServiceHelper(Generic[_T]):
|
class ReloadServiceHelper[_T]:
|
||||||
"""Helper for reload services.
|
"""Helper for reload services.
|
||||||
|
|
||||||
The helper has the following purposes:
|
The helper has the following purposes:
|
||||||
|
@ -3,13 +3,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Callable, Hashable
|
from collections.abc import Callable, Hashable
|
||||||
from typing import Any, TypeVar
|
from typing import Any
|
||||||
|
|
||||||
_KT = TypeVar("_KT", bound=Hashable)
|
|
||||||
_VT = TypeVar("_VT", bound=Callable[..., Any])
|
|
||||||
|
|
||||||
|
|
||||||
class Registry(dict[_KT, _VT]):
|
class Registry[_KT: Hashable, _VT: Callable[..., Any]](dict[_KT, _VT]):
|
||||||
"""Registry of items."""
|
"""Registry of items."""
|
||||||
|
|
||||||
def register(self, name: _KT) -> Callable[[_VT], _VT]:
|
def register(self, name: _KT) -> Callable[[_VT], _VT]:
|
||||||
|
@ -3,13 +3,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from typing import Any, TypeVar
|
from typing import Any
|
||||||
|
|
||||||
_KT = TypeVar("_KT")
|
|
||||||
_VT = TypeVar("_VT")
|
|
||||||
|
|
||||||
|
|
||||||
class LimitedSizeDict(OrderedDict[_KT, _VT]):
|
class LimitedSizeDict[_KT, _VT](OrderedDict[_KT, _VT]):
|
||||||
"""OrderedDict limited in size."""
|
"""OrderedDict limited in size."""
|
||||||
|
|
||||||
def __init__(self, *args: Any, **kwds: Any) -> None:
|
def __init__(self, *args: Any, **kwds: Any) -> None:
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
"""Read only dictionary."""
|
"""Read only dictionary."""
|
||||||
|
|
||||||
from typing import Any, TypeVar
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
def _readonly(*args: Any, **kwargs: Any) -> Any:
|
def _readonly(*args: Any, **kwargs: Any) -> Any:
|
||||||
@ -8,11 +8,7 @@ def _readonly(*args: Any, **kwargs: Any) -> Any:
|
|||||||
raise RuntimeError("Cannot modify ReadOnlyDict")
|
raise RuntimeError("Cannot modify ReadOnlyDict")
|
||||||
|
|
||||||
|
|
||||||
_KT = TypeVar("_KT")
|
class ReadOnlyDict[_KT, _VT](dict[_KT, _VT]):
|
||||||
_VT = TypeVar("_VT")
|
|
||||||
|
|
||||||
|
|
||||||
class ReadOnlyDict(dict[_KT, _VT]):
|
|
||||||
"""Read only version of dict that is compatible with dict types."""
|
"""Read only version of dict that is compatible with dict types."""
|
||||||
|
|
||||||
__setitem__ = _readonly
|
__setitem__ = _readonly
|
||||||
|
@ -3,13 +3,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Generic, TypeVarTuple
|
from typing import Any
|
||||||
|
|
||||||
_Ts = TypeVarTuple("_Ts")
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class _SignalTypeBase(Generic[*_Ts]):
|
class _SignalTypeBase[*_Ts]:
|
||||||
"""Generic base class for SignalType."""
|
"""Generic base class for SignalType."""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
@ -30,12 +28,12 @@ class _SignalTypeBase(Generic[*_Ts]):
|
|||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, eq=False)
|
@dataclass(frozen=True, eq=False)
|
||||||
class SignalType(_SignalTypeBase[*_Ts]):
|
class SignalType[*_Ts](_SignalTypeBase[*_Ts]):
|
||||||
"""Generic string class for signal to improve typing."""
|
"""Generic string class for signal to improve typing."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, eq=False)
|
@dataclass(frozen=True, eq=False)
|
||||||
class SignalTypeFormat(_SignalTypeBase[*_Ts]):
|
class SignalTypeFormat[*_Ts](_SignalTypeBase[*_Ts]):
|
||||||
"""Generic string class for signal. Requires call to 'format' before use."""
|
"""Generic string class for signal. Requires call to 'format' before use."""
|
||||||
|
|
||||||
def format(self, *args: Any, **kwargs: Any) -> SignalType[*_Ts]:
|
def format(self, *args: Any, **kwargs: Any) -> SignalType[*_Ts]:
|
||||||
|
@ -17,7 +17,7 @@ import pathlib
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from types import FrameType, ModuleType
|
from types import FrameType, ModuleType
|
||||||
from typing import Any, NoReturn, TypeVar
|
from typing import Any, NoReturn
|
||||||
from unittest.mock import AsyncMock, Mock, patch
|
from unittest.mock import AsyncMock, Mock, patch
|
||||||
|
|
||||||
from aiohttp.test_utils import unused_port as get_test_instance_port # noqa: F401
|
from aiohttp.test_utils import unused_port as get_test_instance_port # noqa: F401
|
||||||
@ -199,10 +199,7 @@ def get_test_home_assistant() -> Generator[HomeAssistant, None, None]:
|
|||||||
loop.close()
|
loop.close()
|
||||||
|
|
||||||
|
|
||||||
_T = TypeVar("_T", bound=Mapping[str, Any] | Sequence[Any])
|
class StoreWithoutWriteLoad[_T: (Mapping[str, Any] | Sequence[Any])](storage.Store[_T]):
|
||||||
|
|
||||||
|
|
||||||
class StoreWithoutWriteLoad(storage.Store[_T]):
|
|
||||||
"""Fake store that does not write or load. Used for testing."""
|
"""Fake store that does not write or load. Used for testing."""
|
||||||
|
|
||||||
async def async_save(self, *args: Any, **kwargs: Any) -> None:
|
async def async_save(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user