Use PEP 695 for simple type aliases (#117633)

This commit is contained in:
Marc Mueller 2024-05-17 14:42:21 +02:00 committed by GitHub
parent 4edee94a81
commit 87bb7ced79
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
78 changed files with 139 additions and 140 deletions

View file

@ -34,9 +34,9 @@ EVENT_USER_ADDED = "user_added"
EVENT_USER_UPDATED = "user_updated" EVENT_USER_UPDATED = "user_updated"
EVENT_USER_REMOVED = "user_removed" EVENT_USER_REMOVED = "user_removed"
_MfaModuleDict = dict[str, MultiFactorAuthModule] type _MfaModuleDict = dict[str, MultiFactorAuthModule]
_ProviderKey = tuple[str, str | None] type _ProviderKey = tuple[str, str | None]
_ProviderDict = dict[_ProviderKey, AuthProvider] type _ProviderDict = dict[_ProviderKey, AuthProvider]
class InvalidAuthError(Exception): class InvalidAuthError(Exception):

View file

@ -88,7 +88,7 @@ class NotifySetting:
target: str | None = attr.ib(default=None) target: str | None = attr.ib(default=None)
_UsersDict = dict[str, NotifySetting] type _UsersDict = dict[str, NotifySetting]
@MULTI_FACTOR_AUTH_MODULES.register("notify") @MULTI_FACTOR_AUTH_MODULES.register("notify")

View file

@ -4,17 +4,17 @@ from collections.abc import Mapping
# MyPy doesn't support recursion yet. So writing it out as far as we need. # MyPy doesn't support recursion yet. So writing it out as far as we need.
ValueType = ( type ValueType = (
# Example: entities.all = { read: true, control: true } # Example: entities.all = { read: true, control: true }
Mapping[str, bool] | bool | None Mapping[str, bool] | bool | None
) )
# Example: entities.domains = { light: … } # Example: entities.domains = { light: … }
SubCategoryDict = Mapping[str, ValueType] type SubCategoryDict = Mapping[str, ValueType]
SubCategoryType = SubCategoryDict | bool | None type SubCategoryType = SubCategoryDict | bool | None
CategoryType = ( type CategoryType = (
# Example: entities.domains # Example: entities.domains
Mapping[str, SubCategoryType] Mapping[str, SubCategoryType]
# Example: entities.all # Example: entities.all
@ -24,4 +24,4 @@ CategoryType = (
) )
# Example: { entities: … } # Example: { entities: … }
PolicyType = Mapping[str, CategoryType] type PolicyType = Mapping[str, CategoryType]

View file

@ -10,8 +10,8 @@ from .const import SUBCAT_ALL
from .models import PermissionLookup from .models import PermissionLookup
from .types import CategoryType, SubCategoryDict, ValueType from .types import CategoryType, SubCategoryDict, ValueType
LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None] type LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None]
SubCatLookupType = dict[str, LookupFunc] type SubCatLookupType = dict[str, LookupFunc]
def lookup_all( def lookup_all(

View file

@ -28,8 +28,8 @@ from .. import InvalidAuthError
from ..models import AuthFlowResult, Credentials, RefreshToken, UserMeta from ..models import AuthFlowResult, Credentials, RefreshToken, UserMeta
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow
IPAddress = IPv4Address | IPv6Address type IPAddress = IPv4Address | IPv6Address
IPNetwork = IPv4Network | IPv6Network type IPNetwork = IPv4Network | IPv6Network
CONF_TRUSTED_NETWORKS = "trusted_networks" CONF_TRUSTED_NETWORKS = "trusted_networks"
CONF_TRUSTED_USERS = "trusted_users" CONF_TRUSTED_USERS = "trusted_users"

View file

@ -349,7 +349,7 @@ class PipelineEvent:
timestamp: str = field(default_factory=lambda: dt_util.utcnow().isoformat()) timestamp: str = field(default_factory=lambda: dt_util.utcnow().isoformat())
PipelineEventCallback = Callable[[PipelineEvent], None] type PipelineEventCallback = Callable[[PipelineEvent], None]
@dataclass(frozen=True) @dataclass(frozen=True)

View file

@ -164,8 +164,8 @@ from . import indieauth, login_flow, mfa_setup_flow
DOMAIN = "auth" DOMAIN = "auth"
STRICT_CONNECTION_URL = "/auth/strict_connection/temp_token" STRICT_CONNECTION_URL = "/auth/strict_connection/temp_token"
StoreResultType = Callable[[str, Credentials], str] type StoreResultType = Callable[[str, Credentials], str]
RetrieveResultType = Callable[[str, str], Credentials | None] type RetrieveResultType = Callable[[str, str], Credentials | None]
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN) CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)

View file

@ -8,5 +8,5 @@ from enum import Enum
from home_assistant_bluetooth import BluetoothServiceInfoBleak from home_assistant_bluetooth import BluetoothServiceInfoBleak
BluetoothChange = Enum("BluetoothChange", "ADVERTISEMENT") BluetoothChange = Enum("BluetoothChange", "ADVERTISEMENT")
BluetoothCallback = Callable[[BluetoothServiceInfoBleak, BluetoothChange], None] type BluetoothCallback = Callable[[BluetoothServiceInfoBleak, BluetoothChange], None]
ProcessAdvertisementCallback = Callable[[BluetoothServiceInfoBleak], bool] type ProcessAdvertisementCallback = Callable[[BluetoothServiceInfoBleak], bool]

View file

@ -88,8 +88,8 @@ class Timespan:
return f"[{self.start}, {self.end})" return f"[{self.start}, {self.end})"
EventFetcher = Callable[[Timespan], Awaitable[list[CalendarEvent]]] type EventFetcher = Callable[[Timespan], Awaitable[list[CalendarEvent]]]
QueuedEventFetcher = Callable[[Timespan], Awaitable[list[QueuedCalendarEvent]]] type QueuedEventFetcher = Callable[[Timespan], Awaitable[list[QueuedCalendarEvent]]]
def get_entity(hass: HomeAssistant, entity_id: str) -> CalendarEntity: def get_entity(hass: HomeAssistant, entity_id: str) -> CalendarEntity:

View file

@ -335,7 +335,7 @@ def _get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera:
# stream_id: A unique id for the stream, used to update an existing source # stream_id: A unique id for the stream, used to update an existing source
# The output is the SDP answer, or None if the source or offer is not eligible. # The output is the SDP answer, or None if the source or offer is not eligible.
# The Callable may throw HomeAssistantError on failure. # The Callable may throw HomeAssistantError on failure.
RtspToWebRtcProviderType = Callable[[str, str, str], Awaitable[str | None]] type RtspToWebRtcProviderType = Callable[[str, str, str], Awaitable[str | None]]
def async_register_rtsp_to_web_rtc_provider( def async_register_rtsp_to_web_rtc_provider(

View file

@ -21,7 +21,9 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER
from .coordinator import CanaryDataUpdateCoordinator from .coordinator import CanaryDataUpdateCoordinator
SensorTypeItem = tuple[str, str | None, str | None, SensorDeviceClass | None, list[str]] type SensorTypeItem = tuple[
str, str | None, str | None, SensorDeviceClass | None, list[str]
]
SENSOR_VALUE_PRECISION: Final = 2 SENSOR_VALUE_PRECISION: Final = 2
ATTR_AIR_QUALITY: Final = "air_quality" ATTR_AIR_QUALITY: Final = "air_quality"

View file

@ -49,7 +49,7 @@ SERVICE_CONFIGURE = "configure"
STATE_CONFIGURE = "configure" STATE_CONFIGURE = "configure"
STATE_CONFIGURED = "configured" STATE_CONFIGURED = "configured"
ConfiguratorCallback = Callable[[list[dict[str, str]]], None] type ConfiguratorCallback = Callable[[list[dict[str, str]]], None]
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN) CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)

View file

@ -9,7 +9,7 @@ from enum import Enum
from functools import wraps from functools import wraps
import logging import logging
from types import ModuleType from types import ModuleType
from typing import TYPE_CHECKING, Any, Literal, TypeAlias, overload from typing import TYPE_CHECKING, Any, Literal, overload
import voluptuous as vol import voluptuous as vol
import voluptuous_serialize import voluptuous_serialize
@ -49,7 +49,7 @@ if TYPE_CHECKING:
from .condition import DeviceAutomationConditionProtocol from .condition import DeviceAutomationConditionProtocol
from .trigger import DeviceAutomationTriggerProtocol from .trigger import DeviceAutomationTriggerProtocol
DeviceAutomationPlatformType: TypeAlias = ( type DeviceAutomationPlatformType = (
ModuleType ModuleType
| DeviceAutomationTriggerProtocol | DeviceAutomationTriggerProtocol
| DeviceAutomationConditionProtocol | DeviceAutomationConditionProtocol

View file

@ -40,7 +40,7 @@ from .data import get_domain_data
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
FlowInput = Mapping[str, Any] | None type FlowInput = Mapping[str, Any] | None
class ConnectError(IntegrationError): class ConnectError(IntegrationError):

View file

@ -121,7 +121,7 @@ class WaterSourceType(TypedDict):
number_energy_price: float | None # Price for energy ($/m³) number_energy_price: float | None # Price for energy ($/m³)
SourceType = ( type SourceType = (
GridSourceType GridSourceType
| SolarSourceType | SolarSourceType
| BatterySourceType | BatterySourceType

View file

@ -14,8 +14,8 @@ class SolarForecastType(TypedDict):
wh_hours: dict[str, float | int] wh_hours: dict[str, float | int]
GetSolarForecastType = Callable[ type GetSolarForecastType = Callable[
[HomeAssistant, str], Awaitable["SolarForecastType | None"] [HomeAssistant, str], Awaitable[SolarForecastType | None]
] ]

View file

@ -33,12 +33,12 @@ from .data import (
from .types import EnergyPlatform, GetSolarForecastType, SolarForecastType from .types import EnergyPlatform, GetSolarForecastType, SolarForecastType
from .validate import async_validate from .validate import async_validate
EnergyWebSocketCommandHandler = Callable[ type EnergyWebSocketCommandHandler = Callable[
[HomeAssistant, websocket_api.ActiveConnection, "dict[str, Any]", "EnergyManager"], [HomeAssistant, websocket_api.ActiveConnection, dict[str, Any], EnergyManager],
None, None,
] ]
AsyncEnergyWebSocketCommandHandler = Callable[ type AsyncEnergyWebSocketCommandHandler = Callable[
[HomeAssistant, websocket_api.ActiveConnection, "dict[str, Any]", "EnergyManager"], [HomeAssistant, websocket_api.ActiveConnection, dict[str, Any], EnergyManager],
Awaitable[None], Awaitable[None],
] ]

View file

@ -30,7 +30,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
FirmataPinType = int | str type FirmataPinType = int | str
class FirmataBoard: class FirmataBoard:

View file

@ -8,7 +8,7 @@ from homeassistant.helpers.typing import StateType
DOMAIN: Final = "fronius" DOMAIN: Final = "fronius"
SolarNetId = str type SolarNetId = str
SOLAR_NET_DISCOVERY_NEW: Final = "fronius_discovery_new" SOLAR_NET_DISCOVERY_NEW: Final = "fronius_discovery_new"
SOLAR_NET_ID_POWER_FLOW: SolarNetId = "power_flow" SOLAR_NET_ID_POWER_FLOW: SolarNetId = "power_flow"
SOLAR_NET_ID_SYSTEM: SolarNetId = "system" SOLAR_NET_ID_SYSTEM: SolarNetId = "system"

View file

@ -115,7 +115,7 @@ async def async_setup_platform(
on_new_monitor(monitor) on_new_monitor(monitor)
UnderlyingSensorType = ( type UnderlyingSensorType = (
greeneye.monitor.Channel greeneye.monitor.Channel
| greeneye.monitor.PulseCounter | greeneye.monitor.PulseCounter
| greeneye.monitor.TemperatureSensor | greeneye.monitor.TemperatureSensor

View file

@ -10,8 +10,8 @@ from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
NoParamCallback = HassJob[[], Any] | None type NoParamCallback = HassJob[[], Any] | None
ActivityCallback = HassJob[[tuple], Any] | None type ActivityCallback = HassJob[[tuple], Any] | None
class HarmonyCallback(NamedTuple): class HarmonyCallback(NamedTuple):

View file

@ -57,9 +57,9 @@ BLE_AVAILABILITY_CHECK_INTERVAL = 1800 # seconds
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
AddAccessoryCb = Callable[[Accessory], bool] type AddAccessoryCb = Callable[[Accessory], bool]
AddServiceCb = Callable[[Service], bool] type AddServiceCb = Callable[[Service], bool]
AddCharacteristicCb = Callable[[Characteristic], bool] type AddCharacteristicCb = Callable[[Characteristic], bool]
def valid_serial_number(serial: str) -> bool: def valid_serial_number(serial: str) -> bool:

View file

@ -12,7 +12,7 @@ from homeassistant.core import Event, HomeAssistant
from .const import CONTROLLER from .const import CONTROLLER
from .storage import async_get_entity_storage from .storage import async_get_entity_storage
IidTuple = tuple[int, int | None, int | None] type IidTuple = tuple[int, int | None, int | None]
def unique_id_to_iids(unique_id: str) -> IidTuple | None: def unique_id_to_iids(unique_id: str) -> IidTuple | None:

View file

@ -34,7 +34,7 @@ _LOGGER = logging.getLogger(__name__)
_DEVICE_SCAN = f"{DEVICE_TRACKER_DOMAIN}/device_scan" _DEVICE_SCAN = f"{DEVICE_TRACKER_DOMAIN}/device_scan"
_HostType = dict[str, Any] type _HostType = dict[str, Any]
def _get_hosts( def _get_hosts(

View file

@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
from functools import partial from functools import partial
from typing import TypeAlias
from aiohue.v2 import HueBridgeV2 from aiohue.v2 import HueBridgeV2
from aiohue.v2.controllers.config import ( from aiohue.v2.controllers.config import (
@ -37,10 +36,8 @@ from ..bridge import HueBridge
from ..const import DOMAIN from ..const import DOMAIN
from .entity import HueBaseEntity from .entity import HueBaseEntity
SensorType: TypeAlias = ( type SensorType = CameraMotion | Contact | Motion | EntertainmentConfiguration | Tamper
CameraMotion | Contact | Motion | EntertainmentConfiguration | Tamper type ControllerType = (
)
ControllerType: TypeAlias = (
CameraMotionController CameraMotionController
| ContactController | ContactController
| MotionController | MotionController

View file

@ -2,7 +2,7 @@
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, TypeAlias from typing import TYPE_CHECKING
from aiohue.v2.controllers.base import BaseResourcesController from aiohue.v2.controllers.base import BaseResourcesController
from aiohue.v2.controllers.events import EventType from aiohue.v2.controllers.events import EventType
@ -24,7 +24,7 @@ if TYPE_CHECKING:
from aiohue.v2.models.light_level import LightLevel from aiohue.v2.models.light_level import LightLevel
from aiohue.v2.models.motion import Motion from aiohue.v2.models.motion import Motion
HueResource: TypeAlias = Light | DevicePower | GroupedLight | LightLevel | Motion type HueResource = Light | DevicePower | GroupedLight | LightLevel | Motion
RESOURCE_TYPE_NAMES = { RESOURCE_TYPE_NAMES = {

View file

@ -3,7 +3,7 @@
from __future__ import annotations from __future__ import annotations
from functools import partial from functools import partial
from typing import Any, TypeAlias from typing import Any
from aiohue.v2 import HueBridgeV2 from aiohue.v2 import HueBridgeV2
from aiohue.v2.controllers.events import EventType from aiohue.v2.controllers.events import EventType
@ -34,8 +34,8 @@ from ..bridge import HueBridge
from ..const import DOMAIN from ..const import DOMAIN
from .entity import HueBaseEntity from .entity import HueBaseEntity
SensorType: TypeAlias = DevicePower | LightLevel | Temperature | ZigbeeConnectivity type SensorType = DevicePower | LightLevel | Temperature | ZigbeeConnectivity
ControllerType: TypeAlias = ( type ControllerType = (
DevicePowerController DevicePowerController
| LightLevelController | LightLevelController
| TemperatureController | TemperatureController

View file

@ -140,7 +140,7 @@ class TimerEventType(StrEnum):
"""Timer finished without being cancelled.""" """Timer finished without being cancelled."""
TimerHandler = Callable[[TimerEventType, TimerInfo], None] type TimerHandler = Callable[[TimerEventType, TimerInfo], None]
class TimerNotFoundError(intent.IntentHandleError): class TimerNotFoundError(intent.IntentHandleError):

View file

@ -86,8 +86,8 @@ ATTR_SOURCE: Final = "source"
# dispatcher signal for KNX interface device triggers # dispatcher signal for KNX interface device triggers
SIGNAL_KNX_TELEGRAM_DICT: Final = "knx_telegram_dict" SIGNAL_KNX_TELEGRAM_DICT: Final = "knx_telegram_dict"
AsyncMessageCallbackType = Callable[[Telegram], Awaitable[None]] type AsyncMessageCallbackType = Callable[[Telegram], Awaitable[None]]
MessageCallbackType = Callable[[Telegram], None] type MessageCallbackType = Callable[[Telegram], None]
SERVICE_KNX_SEND: Final = "send" SERVICE_KNX_SEND: Final = "send"
SERVICE_KNX_ATTR_PAYLOAD: Final = "payload" SERVICE_KNX_ATTR_PAYLOAD: Final = "payload"

View file

@ -19,7 +19,7 @@ class KrakenResponseEntry(TypedDict):
opening_price: float opening_price: float
KrakenResponse = dict[str, KrakenResponseEntry] type KrakenResponse = dict[str, KrakenResponseEntry]
DEFAULT_SCAN_INTERVAL = 60 DEFAULT_SCAN_INTERVAL = 60

View file

@ -6,7 +6,7 @@ import asyncio
from copy import deepcopy from copy import deepcopy
from itertools import chain from itertools import chain
import re import re
from typing import TypeAlias, cast from typing import cast
import pypck import pypck
import voluptuous as vol import voluptuous as vol
@ -60,12 +60,10 @@ from .const import (
) )
# typing # typing
AddressType = tuple[int, int, bool] type AddressType = tuple[int, int, bool]
DeviceConnectionType: TypeAlias = ( type DeviceConnectionType = pypck.module.ModuleConnection | pypck.module.GroupConnection
pypck.module.ModuleConnection | pypck.module.GroupConnection
)
InputType = type[pypck.inputs.Input] type InputType = type[pypck.inputs.Input]
# Regex for address validation # Regex for address validation
PATTERN_ADDRESS = re.compile( PATTERN_ADDRESS = re.compile(

View file

@ -13,7 +13,7 @@ from matter_server.client.models.node import MatterEndpoint
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.entity import EntityDescription
SensorValueTypes = type[ type SensorValueTypes = type[
clusters.uint | int | clusters.Nullable | clusters.float32 | float clusters.uint | int | clusters.Nullable | clusters.float32 | float
] ]

View file

@ -467,7 +467,7 @@ async def websocket_subscribe(
connection.send_message(websocket_api.result_message(msg["id"])) connection.send_message(websocket_api.result_message(msg["id"]))
ConnectionStatusCallback = Callable[[bool], None] type ConnectionStatusCallback = Callable[[bool], None]
@callback @callback

View file

@ -99,9 +99,9 @@ UNSUBSCRIBE_COOLDOWN = 0.1
TIMEOUT_ACK = 10 TIMEOUT_ACK = 10
RECONNECT_INTERVAL_SECONDS = 10 RECONNECT_INTERVAL_SECONDS = 10
SocketType = socket.socket | ssl.SSLSocket | Any type SocketType = socket.socket | ssl.SSLSocket | Any
SubscribePayloadType = str | bytes # Only bytes if encoding is None type SubscribePayloadType = str | bytes # Only bytes if encoding is None
def publish( def publish(

View file

@ -44,7 +44,7 @@ _LOGGER = logging.getLogger(__name__)
ATTR_THIS = "this" ATTR_THIS = "this"
PublishPayloadType = str | bytes | int | float | None type PublishPayloadType = str | bytes | int | float | None
@dataclass @dataclass
@ -69,8 +69,8 @@ class ReceiveMessage:
timestamp: float timestamp: float
AsyncMessageCallbackType = Callable[[ReceiveMessage], Coroutine[Any, Any, None]] type AsyncMessageCallbackType = Callable[[ReceiveMessage], Coroutine[Any, Any, None]]
MessageCallbackType = Callable[[ReceiveMessage], None] type MessageCallbackType = Callable[[ReceiveMessage], None]
class SubscriptionDebugInfo(TypedDict): class SubscriptionDebugInfo(TypedDict):

View file

@ -19,7 +19,7 @@ CONF_TOPIC_IN_PREFIX: Final = "topic_in_prefix"
CONF_TOPIC_OUT_PREFIX: Final = "topic_out_prefix" CONF_TOPIC_OUT_PREFIX: Final = "topic_out_prefix"
CONF_VERSION: Final = "version" CONF_VERSION: Final = "version"
CONF_GATEWAY_TYPE: Final = "gateway_type" CONF_GATEWAY_TYPE: Final = "gateway_type"
ConfGatewayType = Literal["Serial", "TCP", "MQTT"] type ConfGatewayType = Literal["Serial", "TCP", "MQTT"]
CONF_GATEWAY_TYPE_SERIAL: ConfGatewayType = "Serial" CONF_GATEWAY_TYPE_SERIAL: ConfGatewayType = "Serial"
CONF_GATEWAY_TYPE_TCP: ConfGatewayType = "TCP" CONF_GATEWAY_TYPE_TCP: ConfGatewayType = "TCP"
CONF_GATEWAY_TYPE_MQTT: ConfGatewayType = "MQTT" CONF_GATEWAY_TYPE_MQTT: ConfGatewayType = "MQTT"
@ -55,16 +55,16 @@ class NodeDiscoveryInfo(TypedDict):
SERVICE_SEND_IR_CODE: Final = "send_ir_code" SERVICE_SEND_IR_CODE: Final = "send_ir_code"
SensorType = str type SensorType = str
# S_DOOR, S_MOTION, S_SMOKE, ... # S_DOOR, S_MOTION, S_SMOKE, ...
ValueType = str type ValueType = str
# V_TRIPPED, V_ARMED, V_STATUS, V_PERCENTAGE, ... # V_TRIPPED, V_ARMED, V_STATUS, V_PERCENTAGE, ...
GatewayId = str type GatewayId = str
# a unique id generated by config_flow.py and stored in the ConfigEntry as the entry id. # a unique id generated by config_flow.py and stored in the ConfigEntry as the entry id.
DevId = tuple[GatewayId, int, int, int] type DevId = tuple[GatewayId, int, int, int]
# describes the backend of a hass entity. # describes the backend of a hass entity.
# Contents are: GatewayId, node_id, child_id, v_type as int # Contents are: GatewayId, node_id, child_id, v_type as int
# #

View file

@ -37,19 +37,19 @@ ZEROCONF_MAP: Final[dict[str, str]] = {
"stretch": "Stretch", "stretch": "Stretch",
} }
NumberType = Literal[ type NumberType = Literal[
"maximum_boiler_temperature", "maximum_boiler_temperature",
"max_dhw_temperature", "max_dhw_temperature",
"temperature_offset", "temperature_offset",
] ]
SelectType = Literal[ type SelectType = Literal[
"select_dhw_mode", "select_dhw_mode",
"select_gateway_mode", "select_gateway_mode",
"select_regulation_mode", "select_regulation_mode",
"select_schedule", "select_schedule",
] ]
SelectOptionsType = Literal[ type SelectOptionsType = Literal[
"dhw_modes", "dhw_modes",
"gateway_modes", "gateway_modes",
"regulation_modes", "regulation_modes",

View file

@ -17,8 +17,8 @@ from .const import DOMAIN
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
UnavailableCallback = Callable[[bluetooth.BluetoothServiceInfoBleak], None] type UnavailableCallback = Callable[[bluetooth.BluetoothServiceInfoBleak], None]
Cancellable = Callable[[], None] type Cancellable = Callable[[], None]
def async_last_service_info( def async_last_service_info(

View file

@ -40,7 +40,7 @@ EXPANDABLE_MEDIA_TYPES = [
MediaType.CHANNELS, MediaType.CHANNELS,
] ]
GetBrowseImageUrlType = Callable[[str, str, "str | None"], str | None] type GetBrowseImageUrlType = Callable[[str, str, str | None], str | None]
def get_thumbnail_url_full( def get_thumbnail_url_full(

View file

@ -15,7 +15,7 @@ from homeassistant.const import (
) )
from homeassistant.util import slugify from homeassistant.util import slugify
ScreenLogicDataPath = tuple[str | int, ...] type ScreenLogicDataPath = tuple[str | int, ...]
DOMAIN = "screenlogic" DOMAIN = "screenlogic"
DEFAULT_SCAN_INTERVAL = 30 DEFAULT_SCAN_INTERVAL = 30

View file

@ -30,7 +30,7 @@ CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
PLATFORMS = [Platform.CLIMATE] PLATFORMS = [Platform.CLIMATE]
SENZDataUpdateCoordinator = DataUpdateCoordinator[dict[str, Thermostat]] type SENZDataUpdateCoordinator = DataUpdateCoordinator[dict[str, Thermostat]]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

View file

@ -3,4 +3,4 @@
from simplipy.system.v2 import SystemV2 from simplipy.system.v2 import SystemV2
from simplipy.system.v3 import SystemV3 from simplipy.system.v3 import SystemV3
SystemType = SystemV2 | SystemV3 type SystemType = SystemV2 | SystemV3

View file

@ -43,7 +43,7 @@ from .speaker import SonosMedia, SonosSpeaker
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
GetBrowseImageUrlType = Callable[[str, str, "str | None"], str] type GetBrowseImageUrlType = Callable[[str, str, str | None], str]
def get_thumbnail_url_full( def get_thumbnail_url_full(

View file

@ -28,7 +28,7 @@ LEVEL_TYPES = {
"music_surround_level": (-15, 15), "music_surround_level": (-15, 15),
} }
SocoFeatures = list[tuple[str, tuple[int, int]]] type SocoFeatures = list[tuple[str, tuple[int, int]]]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)

View file

@ -126,7 +126,7 @@ class SsdpServiceInfo(BaseServiceInfo):
SsdpChange = Enum("SsdpChange", "ALIVE BYEBYE UPDATE") SsdpChange = Enum("SsdpChange", "ALIVE BYEBYE UPDATE")
SsdpHassJobCallback = HassJob[ type SsdpHassJobCallback = HassJob[
[SsdpServiceInfo, SsdpChange], Coroutine[Any, Any, None] | None [SsdpServiceInfo, SsdpChange], Coroutine[Any, Any, None] | None
] ]

View file

@ -13,7 +13,7 @@ from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = getLogger(__name__) _LOGGER = getLogger(__name__)
Status = dict[str, Any] | None type Status = dict[str, Any] | None
class SwitchBotCoordinator(DataUpdateCoordinator[Status]): class SwitchBotCoordinator(DataUpdateCoordinator[Status]):

View file

@ -19,7 +19,7 @@ from homeassistant.core import Event, HomeAssistant, ServiceCall, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
KeyType = tuple[str, tuple[str, int], tuple[str, int, str] | None] type KeyType = tuple[str, tuple[str, int], tuple[str, int, str] | None]
CONF_MAX_ENTRIES = "max_entries" CONF_MAX_ENTRIES = "max_entries"
CONF_FIRE_EVENT = "fire_event" CONF_FIRE_EVENT = "fire_event"

View file

@ -45,7 +45,7 @@ TASMOTA_DISCOVERY_INSTANCE = "tasmota_discovery_instance"
MQTT_TOPIC_URL = "https://tasmota.github.io/docs/Home-Assistant/#tasmota-integration" MQTT_TOPIC_URL = "https://tasmota.github.io/docs/Home-Assistant/#tasmota-integration"
SetupDeviceCallback = Callable[[TasmotaDeviceConfig, str], Awaitable[None]] type SetupDeviceCallback = Callable[[TasmotaDeviceConfig, str], Awaitable[None]]
def clear_discovery_hash( def clear_discovery_hash(

View file

@ -36,7 +36,7 @@ from .const import (
CONF_BEFORE_TIME, CONF_BEFORE_TIME,
) )
SunEventType = Literal["sunrise", "sunset"] type SunEventType = Literal["sunrise", "sunset"]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)

View file

@ -35,7 +35,7 @@ class TraccarServerCoordinatorDataDevice(TypedDict):
attributes: dict[str, Any] attributes: dict[str, Any]
TraccarServerCoordinatorData = dict[int, TraccarServerCoordinatorDataDevice] type TraccarServerCoordinatorData = dict[int, TraccarServerCoordinatorDataDevice]
class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorData]): class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorData]):

View file

@ -40,7 +40,7 @@ TRACE_CONFIG_SCHEMA = {
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN) CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
TraceData = dict[str, LimitedSizeDict[str, BaseTrace]] type TraceData = dict[str, LimitedSizeDict[str, BaseTrace]]
@callback @callback

View file

@ -18,4 +18,4 @@ DOMAIN = "tts"
DATA_TTS_MANAGER = "tts_manager" DATA_TTS_MANAGER = "tts_manager"
TtsAudioType = tuple[str | None, bytes | None] type TtsAudioType = tuple[str | None, bytes | None]

View file

@ -43,7 +43,7 @@ from .const import (
from .utils import async_dispatch_id as _ufpd, async_get_devices_by_type from .utils import async_dispatch_id as _ufpd, async_get_devices_by_type
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
ProtectDeviceType = ProtectAdoptableDeviceModel | NVR type ProtectDeviceType = ProtectAdoptableDeviceModel | NVR
@callback @callback

View file

@ -26,8 +26,8 @@ current_connection = ContextVar["ActiveConnection | None"](
"current_connection", default=None "current_connection", default=None
) )
MessageHandler = Callable[[HomeAssistant, "ActiveConnection", dict[str, Any]], None] type MessageHandler = Callable[[HomeAssistant, ActiveConnection, dict[str, Any]], None]
BinaryHandler = Callable[[HomeAssistant, "ActiveConnection", bytes], None] type BinaryHandler = Callable[[HomeAssistant, ActiveConnection, bytes], None]
class ActiveConnection: class ActiveConnection:

View file

@ -11,11 +11,11 @@ if TYPE_CHECKING:
from .connection import ActiveConnection from .connection import ActiveConnection
WebSocketCommandHandler = Callable[ type WebSocketCommandHandler = Callable[
[HomeAssistant, "ActiveConnection", dict[str, Any]], None [HomeAssistant, ActiveConnection, dict[str, Any]], None
] ]
AsyncWebSocketCommandHandler = Callable[ type AsyncWebSocketCommandHandler = Callable[
[HomeAssistant, "ActiveConnection", dict[str, Any]], Awaitable[None] [HomeAssistant, ActiveConnection, dict[str, Any]], Awaitable[None]
] ]
DOMAIN: Final = "websocket_api" DOMAIN: Final = "websocket_api"

View file

@ -44,8 +44,8 @@ WEMO_MODEL_DISPATCH = {
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DispatchCallback = Callable[[DeviceCoordinator], Coroutine[Any, Any, None]] type DispatchCallback = Callable[[DeviceCoordinator], Coroutine[Any, Any, None]]
HostPortTuple = tuple[str, int | None] type HostPortTuple = tuple[str, int | None]
def coerce_host_port(value: str) -> HostPortTuple: def coerce_host_port(value: str) -> HostPortTuple:

View file

@ -37,9 +37,9 @@ from .models import async_wemo_data
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# Literal values must match options.error keys from strings.json. # Literal values must match options.error keys from strings.json.
ErrorStringKey = Literal["long_press_requires_subscription"] type ErrorStringKey = Literal["long_press_requires_subscription"]
# Literal values must match options.step.init.data keys from strings.json. # Literal values must match options.step.init.data keys from strings.json.
OptionsFieldKey = Literal["enable_subscription", "enable_long_press"] type OptionsFieldKey = Literal["enable_subscription", "enable_long_press"]
class OptionsValidationError(Exception): class OptionsValidationError(Exception):

View file

@ -245,7 +245,7 @@ ZHA_CONFIG_SCHEMAS = {
ZHA_ALARM_OPTIONS: CONF_ZHA_ALARM_SCHEMA, ZHA_ALARM_OPTIONS: CONF_ZHA_ALARM_SCHEMA,
} }
_ControllerClsType = type[zigpy.application.ControllerApplication] type _ControllerClsType = type[zigpy.application.ControllerApplication]
class RadioType(enum.Enum): class RadioType(enum.Enum):

View file

@ -96,7 +96,7 @@ if TYPE_CHECKING:
from ..entity import ZhaEntity from ..entity import ZhaEntity
from .cluster_handlers import ClusterHandler from .cluster_handlers import ClusterHandler
_LogFilterType = Filter | Callable[[LogRecord], bool] type _LogFilterType = Filter | Callable[[LogRecord], bool]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)

View file

@ -238,7 +238,9 @@ class OperationNotAllowed(ConfigError):
"""Raised when a config entry operation is not allowed.""" """Raised when a config entry operation is not allowed."""
UpdateListenerType = Callable[[HomeAssistant, "ConfigEntry"], Coroutine[Any, Any, None]] type UpdateListenerType = Callable[
[HomeAssistant, ConfigEntry], Coroutine[Any, Any, None]
]
FROZEN_CONFIG_ENTRY_ATTRS = { FROZEN_CONFIG_ENTRY_ATTRS = {
"entry_id", "entry_id",

View file

@ -141,7 +141,7 @@ _UNDEF: dict[Any, Any] = {}
_SENTINEL = object() _SENTINEL = object()
_CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) _CallableT = TypeVar("_CallableT", bound=Callable[..., Any])
_DataT = TypeVar("_DataT", bound=Mapping[str, Any], default=Mapping[str, Any]) _DataT = TypeVar("_DataT", bound=Mapping[str, Any], default=Mapping[str, Any])
CALLBACK_TYPE = Callable[[], None] type CALLBACK_TYPE = Callable[[], None]
CORE_STORAGE_KEY = "core.config" CORE_STORAGE_KEY = "core.config"
CORE_STORAGE_VERSION = 1 CORE_STORAGE_VERSION = 1
@ -152,8 +152,8 @@ DOMAIN = "homeassistant"
# How long to wait to log tasks that are blocking # How long to wait to log tasks that are blocking
BLOCK_LOG_TIMEOUT = 60 BLOCK_LOG_TIMEOUT = 60
ServiceResponse = JsonObjectType | None type ServiceResponse = JsonObjectType | None
EntityServiceResponse = dict[str, ServiceResponse] type EntityServiceResponse = dict[str, ServiceResponse]
class ConfigSource(enum.StrEnum): class ConfigSource(enum.StrEnum):

View file

@ -47,7 +47,7 @@ class EventCategoryRegistryUpdatedData(TypedDict):
category_id: str category_id: str
EventCategoryRegistryUpdated = Event[EventCategoryRegistryUpdatedData] type EventCategoryRegistryUpdated = Event[EventCategoryRegistryUpdatedData]
@dataclass(slots=True, kw_only=True, frozen=True) @dataclass(slots=True, kw_only=True, frozen=True)

View file

@ -55,7 +55,7 @@ class CollectionChangeSet:
item: Any item: Any
ChangeListener = Callable[ type ChangeListener = Callable[
[ [
# Change type # Change type
str, str,
@ -67,7 +67,7 @@ ChangeListener = Callable[
Awaitable[None], Awaitable[None],
] ]
ChangeSetListener = Callable[[Iterable[CollectionChangeSet]], Awaitable[None]] type ChangeSetListener = Callable[[Iterable[CollectionChangeSet]], Awaitable[None]]
class CollectionError(HomeAssistantError): class CollectionError(HomeAssistantError):

View file

@ -115,7 +115,7 @@ class ConditionProtocol(Protocol):
"""Evaluate state based on configuration.""" """Evaluate state based on configuration."""
ConditionCheckerType = Callable[[HomeAssistant, TemplateVarsType], bool | None] type ConditionCheckerType = Callable[[HomeAssistant, TemplateVarsType], bool | None]
def condition_trace_append(variables: TemplateVarsType, path: str) -> TraceElement: def condition_trace_append(variables: TemplateVarsType, path: str) -> TraceElement:

View file

@ -160,7 +160,7 @@ class _EventDeviceRegistryUpdatedData_Update(TypedDict):
changes: dict[str, Any] changes: dict[str, Any]
EventDeviceRegistryUpdatedData = ( type EventDeviceRegistryUpdatedData = (
_EventDeviceRegistryUpdatedData_CreateRemove _EventDeviceRegistryUpdatedData_CreateRemove
| _EventDeviceRegistryUpdatedData_Update | _EventDeviceRegistryUpdatedData_Update
) )

View file

@ -134,14 +134,14 @@ class _EventEntityRegistryUpdatedData_Update(TypedDict):
old_entity_id: NotRequired[str] old_entity_id: NotRequired[str]
EventEntityRegistryUpdatedData = ( type EventEntityRegistryUpdatedData = (
_EventEntityRegistryUpdatedData_CreateRemove _EventEntityRegistryUpdatedData_CreateRemove
| _EventEntityRegistryUpdatedData_Update | _EventEntityRegistryUpdatedData_Update
) )
EntityOptionsType = Mapping[str, Mapping[str, Any]] type EntityOptionsType = Mapping[str, Mapping[str, Any]]
ReadOnlyEntityOptionsType = ReadOnlyDict[str, ReadOnlyDict[str, Any]] type ReadOnlyEntityOptionsType = ReadOnlyDict[str, ReadOnlyDict[str, Any]]
DISPLAY_DICT_OPTIONAL = ( DISPLAY_DICT_OPTIONAL = (
# key, attr_name, convert_to_list # key, attr_name, convert_to_list

View file

@ -1262,7 +1262,7 @@ class TrackTemplateResultInfo:
self.hass.async_run_hass_job(self._job, event, updates) self.hass.async_run_hass_job(self._job, event, updates)
TrackTemplateResultListener = Callable[ type TrackTemplateResultListener = Callable[
[ [
Event[EventStateChangedData] | None, Event[EventStateChangedData] | None,
list[TrackTemplateResult], list[TrackTemplateResult],

View file

@ -53,7 +53,7 @@ class EventFloorRegistryUpdatedData(TypedDict):
floor_id: str floor_id: str
EventFloorRegistryUpdated = Event[EventFloorRegistryUpdatedData] type EventFloorRegistryUpdated = Event[EventFloorRegistryUpdatedData]
@dataclass(slots=True, kw_only=True, frozen=True) @dataclass(slots=True, kw_only=True, frozen=True)

View file

@ -30,7 +30,7 @@ from .json import find_paths_unserializable_data, json_bytes, json_dumps
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
AllowCorsType = Callable[[AbstractRoute | AbstractResource], None] type AllowCorsType = Callable[[AbstractRoute | AbstractResource], None]
KEY_AUTHENTICATED: Final = "ha_authenticated" KEY_AUTHENTICATED: Final = "ha_authenticated"
KEY_ALLOW_ALL_CORS = AppKey[AllowCorsType]("allow_all_cors") KEY_ALLOW_ALL_CORS = AppKey[AllowCorsType]("allow_all_cors")
KEY_ALLOW_CONFIGRED_CORS = AppKey[AllowCorsType]("allow_configured_cors") KEY_ALLOW_CONFIGRED_CORS = AppKey[AllowCorsType]("allow_configured_cors")

View file

@ -35,7 +35,7 @@ from . import (
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_SlotsType = dict[str, Any] type _SlotsType = dict[str, Any]
INTENT_TURN_OFF = "HassTurnOff" INTENT_TURN_OFF = "HassTurnOff"
INTENT_TURN_ON = "HassTurnOn" INTENT_TURN_ON = "HassTurnOn"

View file

@ -53,7 +53,7 @@ class EventLabelRegistryUpdatedData(TypedDict):
label_id: str label_id: str
EventLabelRegistryUpdated = Event[EventLabelRegistryUpdatedData] type EventLabelRegistryUpdated = Event[EventLabelRegistryUpdatedData]
@dataclass(slots=True, frozen=True, kw_only=True) @dataclass(slots=True, frozen=True, kw_only=True)

View file

@ -1311,7 +1311,7 @@ async def _async_stop_scripts_at_shutdown(hass: HomeAssistant, event: Event) ->
) )
_VarsType = dict[str, Any] | MappingProxyType type _VarsType = dict[str, Any] | MappingProxyType
def _referenced_extract_ids(data: Any, key: str, found: set[str]) -> None: def _referenced_extract_ids(data: Any, key: str, found: set[str]) -> None:

View file

@ -4,7 +4,7 @@ from dataclasses import dataclass
from homeassistant.data_entry_flow import BaseServiceInfo from homeassistant.data_entry_flow import BaseServiceInfo
ReceivePayloadType = str | bytes type ReceivePayloadType = str | bytes
@dataclass(slots=True) @dataclass(slots=True)

View file

@ -41,7 +41,7 @@ from .integration_platform import async_process_integration_platforms
PLATFORM = "significant_change" PLATFORM = "significant_change"
DATA_FUNCTIONS: HassKey[dict[str, CheckTypeFunc]] = HassKey("significant_change") DATA_FUNCTIONS: HassKey[dict[str, CheckTypeFunc]] = HassKey("significant_change")
CheckTypeFunc = Callable[ type CheckTypeFunc = Callable[
[ [
HomeAssistant, HomeAssistant,
str, str,
@ -52,7 +52,7 @@ CheckTypeFunc = Callable[
bool | None, bool | None,
] ]
ExtraCheckTypeFunc = Callable[ type ExtraCheckTypeFunc = Callable[
[ [
HomeAssistant, HomeAssistant,
str, str,

View file

@ -22,7 +22,7 @@ DATA_LOCATION_CACHE: HassKey[
ELEVATION_AGNOSTIC_EVENTS = ("noon", "midnight") ELEVATION_AGNOSTIC_EVENTS = ("noon", "midnight")
_AstralSunEventCallable = Callable[..., datetime.datetime] type _AstralSunEventCallable = Callable[..., datetime.datetime]
@callback @callback

View file

@ -14,16 +14,16 @@ from .deprecation import (
dir_with_deprecated_constants, dir_with_deprecated_constants,
) )
GPSType = tuple[float, float] type GPSType = tuple[float, float]
ConfigType = dict[str, Any] type ConfigType = dict[str, Any]
DiscoveryInfoType = dict[str, Any] type DiscoveryInfoType = dict[str, Any]
ServiceDataType = dict[str, Any] type ServiceDataType = dict[str, Any]
StateType = str | int | float | None type StateType = str | int | float | None
TemplateVarsType = Mapping[str, Any] | None type TemplateVarsType = Mapping[str, Any] | None
NoEventData = Mapping[str, Never] type NoEventData = Mapping[str, Never]
# Custom type for recorder Queries # Custom type for recorder Queries
QueryType = Any type QueryType = Any
class UndefinedType(Enum): class UndefinedType(Enum):

View file

@ -215,7 +215,7 @@ class SafeLineLoader(PythonSafeLoader):
) )
LoaderType = FastSafeLoader | PythonSafeLoader type LoaderType = FastSafeLoader | PythonSafeLoader
def load_yaml( def load_yaml(

View file

@ -3,7 +3,7 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable, Coroutine from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any, TypeAlias from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock from unittest.mock import MagicMock
from aiohttp import ClientWebSocketResponse from aiohttp import ClientWebSocketResponse
@ -30,6 +30,6 @@ MqttMockHAClient = MagicMock
"""MagicMock for `homeassistant.components.mqtt.MQTT`.""" """MagicMock for `homeassistant.components.mqtt.MQTT`."""
MqttMockHAClientGenerator = Callable[..., Coroutine[Any, Any, MqttMockHAClient]] MqttMockHAClientGenerator = Callable[..., Coroutine[Any, Any, MqttMockHAClient]]
"""MagicMock generator for `homeassistant.components.mqtt.MQTT`.""" """MagicMock generator for `homeassistant.components.mqtt.MQTT`."""
RecorderInstanceGenerator: TypeAlias = Callable[..., Coroutine[Any, Any, "Recorder"]] type RecorderInstanceGenerator = Callable[..., Coroutine[Any, Any, "Recorder"]]
"""Instance generator for `homeassistant.components.recorder.Recorder`.""" """Instance generator for `homeassistant.components.recorder.Recorder`."""
WebSocketGenerator = Callable[..., Coroutine[Any, Any, MockHAClientWebSocket]] WebSocketGenerator = Callable[..., Coroutine[Any, Any, MockHAClientWebSocket]]