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_REMOVED = "user_removed"
_MfaModuleDict = dict[str, MultiFactorAuthModule]
_ProviderKey = tuple[str, str | None]
_ProviderDict = dict[_ProviderKey, AuthProvider]
type _MfaModuleDict = dict[str, MultiFactorAuthModule]
type _ProviderKey = tuple[str, str | None]
type _ProviderDict = dict[_ProviderKey, AuthProvider]
class InvalidAuthError(Exception):

View File

@ -88,7 +88,7 @@ class NotifySetting:
target: str | None = attr.ib(default=None)
_UsersDict = dict[str, NotifySetting]
type _UsersDict = dict[str, NotifySetting]
@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.
ValueType = (
type ValueType = (
# Example: entities.all = { read: true, control: true }
Mapping[str, bool] | bool | None
)
# 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
Mapping[str, SubCategoryType]
# Example: entities.all
@ -24,4 +24,4 @@ CategoryType = (
)
# 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 .types import CategoryType, SubCategoryDict, ValueType
LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None]
SubCatLookupType = dict[str, LookupFunc]
type LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None]
type SubCatLookupType = dict[str, LookupFunc]
def lookup_all(

View File

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

View File

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

View File

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

View File

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

View File

@ -88,8 +88,8 @@ class Timespan:
return f"[{self.start}, {self.end})"
EventFetcher = Callable[[Timespan], Awaitable[list[CalendarEvent]]]
QueuedEventFetcher = Callable[[Timespan], Awaitable[list[QueuedCalendarEvent]]]
type EventFetcher = Callable[[Timespan], Awaitable[list[CalendarEvent]]]
type QueuedEventFetcher = Callable[[Timespan], Awaitable[list[QueuedCalendarEvent]]]
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
# The output is the SDP answer, or None if the source or offer is not eligible.
# 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(

View File

@ -21,7 +21,9 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER
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
ATTR_AIR_QUALITY: Final = "air_quality"

View File

@ -49,7 +49,7 @@ SERVICE_CONFIGURE = "configure"
STATE_CONFIGURE = "configure"
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)

View File

@ -9,7 +9,7 @@ from enum import Enum
from functools import wraps
import logging
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_serialize
@ -49,7 +49,7 @@ if TYPE_CHECKING:
from .condition import DeviceAutomationConditionProtocol
from .trigger import DeviceAutomationTriggerProtocol
DeviceAutomationPlatformType: TypeAlias = (
type DeviceAutomationPlatformType = (
ModuleType
| DeviceAutomationTriggerProtocol
| DeviceAutomationConditionProtocol

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -57,9 +57,9 @@ BLE_AVAILABILITY_CHECK_INTERVAL = 1800 # seconds
_LOGGER = logging.getLogger(__name__)
AddAccessoryCb = Callable[[Accessory], bool]
AddServiceCb = Callable[[Service], bool]
AddCharacteristicCb = Callable[[Characteristic], bool]
type AddAccessoryCb = Callable[[Accessory], bool]
type AddServiceCb = Callable[[Service], bool]
type AddCharacteristicCb = Callable[[Characteristic], 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 .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:

View File

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

View File

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

View File

@ -2,7 +2,7 @@
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.events import EventType
@ -24,7 +24,7 @@ if TYPE_CHECKING:
from aiohue.v2.models.light_level import LightLevel
from aiohue.v2.models.motion import Motion
HueResource: TypeAlias = Light | DevicePower | GroupedLight | LightLevel | Motion
type HueResource = Light | DevicePower | GroupedLight | LightLevel | Motion
RESOURCE_TYPE_NAMES = {

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@ import asyncio
from copy import deepcopy
from itertools import chain
import re
from typing import TypeAlias, cast
from typing import cast
import pypck
import voluptuous as vol
@ -60,12 +60,10 @@ from .const import (
)
# typing
AddressType = tuple[int, int, bool]
DeviceConnectionType: TypeAlias = (
pypck.module.ModuleConnection | pypck.module.GroupConnection
)
type AddressType = tuple[int, int, bool]
type DeviceConnectionType = pypck.module.ModuleConnection | pypck.module.GroupConnection
InputType = type[pypck.inputs.Input]
type InputType = type[pypck.inputs.Input]
# Regex for address validation
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.helpers.entity import EntityDescription
SensorValueTypes = type[
type SensorValueTypes = type[
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"]))
ConnectionStatusCallback = Callable[[bool], None]
type ConnectionStatusCallback = Callable[[bool], None]
@callback

View File

@ -99,9 +99,9 @@ UNSUBSCRIBE_COOLDOWN = 0.1
TIMEOUT_ACK = 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(

View File

@ -44,7 +44,7 @@ _LOGGER = logging.getLogger(__name__)
ATTR_THIS = "this"
PublishPayloadType = str | bytes | int | float | None
type PublishPayloadType = str | bytes | int | float | None
@dataclass
@ -69,8 +69,8 @@ class ReceiveMessage:
timestamp: float
AsyncMessageCallbackType = Callable[[ReceiveMessage], Coroutine[Any, Any, None]]
MessageCallbackType = Callable[[ReceiveMessage], None]
type AsyncMessageCallbackType = Callable[[ReceiveMessage], Coroutine[Any, Any, None]]
type MessageCallbackType = Callable[[ReceiveMessage], None]
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_VERSION: Final = "version"
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_TCP: ConfGatewayType = "TCP"
CONF_GATEWAY_TYPE_MQTT: ConfGatewayType = "MQTT"
@ -55,16 +55,16 @@ class NodeDiscoveryInfo(TypedDict):
SERVICE_SEND_IR_CODE: Final = "send_ir_code"
SensorType = str
type SensorType = str
# S_DOOR, S_MOTION, S_SMOKE, ...
ValueType = str
type ValueType = str
# 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.
DevId = tuple[GatewayId, int, int, int]
type DevId = tuple[GatewayId, int, int, int]
# describes the backend of a hass entity.
# 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",
}
NumberType = Literal[
type NumberType = Literal[
"maximum_boiler_temperature",
"max_dhw_temperature",
"temperature_offset",
]
SelectType = Literal[
type SelectType = Literal[
"select_dhw_mode",
"select_gateway_mode",
"select_regulation_mode",
"select_schedule",
]
SelectOptionsType = Literal[
type SelectOptionsType = Literal[
"dhw_modes",
"gateway_modes",
"regulation_modes",

View File

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

View File

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

View File

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

View File

@ -30,7 +30,7 @@ CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
PLATFORMS = [Platform.CLIMATE]
SENZDataUpdateCoordinator = DataUpdateCoordinator[dict[str, Thermostat]]
type SENZDataUpdateCoordinator = DataUpdateCoordinator[dict[str, Thermostat]]
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.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__)
GetBrowseImageUrlType = Callable[[str, str, "str | None"], str]
type GetBrowseImageUrlType = Callable[[str, str, str | None], str]
def get_thumbnail_url_full(

View File

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

View File

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

View File

@ -13,7 +13,7 @@ from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = getLogger(__name__)
Status = dict[str, Any] | None
type Status = dict[str, Any] | None
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
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_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"
SetupDeviceCallback = Callable[[TasmotaDeviceConfig, str], Awaitable[None]]
type SetupDeviceCallback = Callable[[TasmotaDeviceConfig, str], Awaitable[None]]
def clear_discovery_hash(

View File

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

View File

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

View File

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

View File

@ -18,4 +18,4 @@ DOMAIN = "tts"
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
_LOGGER = logging.getLogger(__name__)
ProtectDeviceType = ProtectAdoptableDeviceModel | NVR
type ProtectDeviceType = ProtectAdoptableDeviceModel | NVR
@callback

View File

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

View File

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

View File

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

View File

@ -37,9 +37,9 @@ from .models import async_wemo_data
_LOGGER = logging.getLogger(__name__)
# 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.
OptionsFieldKey = Literal["enable_subscription", "enable_long_press"]
type OptionsFieldKey = Literal["enable_subscription", "enable_long_press"]
class OptionsValidationError(Exception):

View File

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

View File

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

View File

@ -238,7 +238,9 @@ class OperationNotAllowed(ConfigError):
"""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 = {
"entry_id",

View File

@ -141,7 +141,7 @@ _UNDEF: dict[Any, Any] = {}
_SENTINEL = object()
_CallableT = TypeVar("_CallableT", bound=Callable[..., 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_VERSION = 1
@ -152,8 +152,8 @@ DOMAIN = "homeassistant"
# How long to wait to log tasks that are blocking
BLOCK_LOG_TIMEOUT = 60
ServiceResponse = JsonObjectType | None
EntityServiceResponse = dict[str, ServiceResponse]
type ServiceResponse = JsonObjectType | None
type EntityServiceResponse = dict[str, ServiceResponse]
class ConfigSource(enum.StrEnum):

View File

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

View File

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

View File

@ -115,7 +115,7 @@ class ConditionProtocol(Protocol):
"""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:

View File

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

View File

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

View File

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

View File

@ -53,7 +53,7 @@ class EventFloorRegistryUpdatedData(TypedDict):
floor_id: str
EventFloorRegistryUpdated = Event[EventFloorRegistryUpdatedData]
type EventFloorRegistryUpdated = Event[EventFloorRegistryUpdatedData]
@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__)
AllowCorsType = Callable[[AbstractRoute | AbstractResource], None]
type AllowCorsType = Callable[[AbstractRoute | AbstractResource], None]
KEY_AUTHENTICATED: Final = "ha_authenticated"
KEY_ALLOW_ALL_CORS = AppKey[AllowCorsType]("allow_all_cors")
KEY_ALLOW_CONFIGRED_CORS = AppKey[AllowCorsType]("allow_configured_cors")

View File

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

View File

@ -53,7 +53,7 @@ class EventLabelRegistryUpdatedData(TypedDict):
label_id: str
EventLabelRegistryUpdated = Event[EventLabelRegistryUpdatedData]
type EventLabelRegistryUpdated = Event[EventLabelRegistryUpdatedData]
@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:

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@
from __future__ import annotations
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 aiohttp import ClientWebSocketResponse
@ -30,6 +30,6 @@ MqttMockHAClient = MagicMock
"""MagicMock for `homeassistant.components.mqtt.MQTT`."""
MqttMockHAClientGenerator = Callable[..., Coroutine[Any, Any, MqttMockHAClient]]
"""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`."""
WebSocketGenerator = Callable[..., Coroutine[Any, Any, MockHAClientWebSocket]]