diff --git a/homeassistant/auth/__init__.py b/homeassistant/auth/__init__.py index 966536f446c..5c401570dee 100644 --- a/homeassistant/auth/__init__.py +++ b/homeassistant/auth/__init__.py @@ -5,7 +5,7 @@ import asyncio from collections import OrderedDict from collections.abc import Mapping from datetime import timedelta -from typing import Any, Optional, cast +from typing import Any, cast import jwt @@ -24,7 +24,7 @@ EVENT_USER_UPDATED = "user_updated" EVENT_USER_REMOVED = "user_removed" _MfaModuleDict = dict[str, MultiFactorAuthModule] -_ProviderKey = tuple[str, Optional[str]] +_ProviderKey = tuple[str, str | None] _ProviderDict = dict[_ProviderKey, AuthProvider] diff --git a/homeassistant/auth/permissions/util.py b/homeassistant/auth/permissions/util.py index 60e68e8b7ca..7a1f102fdf3 100644 --- a/homeassistant/auth/permissions/util.py +++ b/homeassistant/auth/permissions/util.py @@ -3,13 +3,13 @@ from __future__ import annotations from collections.abc import Callable from functools import wraps -from typing import Optional, cast +from typing import cast from .const import SUBCAT_ALL from .models import PermissionLookup from .types import CategoryType, SubCategoryDict, ValueType -LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], Optional[ValueType]] +LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None] SubCatLookupType = dict[str, LookupFunc] diff --git a/homeassistant/components/auth/__init__.py b/homeassistant/components/auth/__init__.py index ac5035de645..01ce39f5fcc 100644 --- a/homeassistant/components/auth/__init__.py +++ b/homeassistant/components/auth/__init__.py @@ -127,7 +127,7 @@ from __future__ import annotations from collections.abc import Callable from datetime import datetime, timedelta from http import HTTPStatus -from typing import Any, Optional, cast +from typing import Any, cast import uuid from aiohttp import web @@ -159,7 +159,7 @@ from . import indieauth, login_flow, mfa_setup_flow DOMAIN = "auth" StoreResultType = Callable[[str, Credentials], str] -RetrieveResultType = Callable[[str, str], Optional[Credentials]] +RetrieveResultType = Callable[[str, str], Credentials | None] @bind_hass diff --git a/homeassistant/components/baf/binary_sensor.py b/homeassistant/components/baf/binary_sensor.py index 8a00a7e8bd5..fcfd0f3241d 100644 --- a/homeassistant/components/baf/binary_sensor.py +++ b/homeassistant/components/baf/binary_sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from typing import Optional, cast +from typing import cast from aiobafi6 import Device @@ -41,7 +41,7 @@ OCCUPANCY_SENSORS = ( key="occupancy", name="Occupancy", device_class=BinarySensorDeviceClass.OCCUPANCY, - value_fn=lambda device: cast(Optional[bool], device.fan_occupancy_detected), + value_fn=lambda device: cast(bool | None, device.fan_occupancy_detected), ), ) diff --git a/homeassistant/components/baf/number.py b/homeassistant/components/baf/number.py index 0e014de6750..1cab994376d 100644 --- a/homeassistant/components/baf/number.py +++ b/homeassistant/components/baf/number.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from typing import Optional, cast +from typing import cast from aiobafi6 import Device @@ -43,7 +43,7 @@ AUTO_COMFORT_NUMBER_DESCRIPTIONS = ( native_min_value=0, native_max_value=SPEED_RANGE[1] - 1, entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[int], device.comfort_min_speed), + value_fn=lambda device: cast(int | None, device.comfort_min_speed), mode=NumberMode.BOX, ), BAFNumberDescription( @@ -52,7 +52,7 @@ AUTO_COMFORT_NUMBER_DESCRIPTIONS = ( native_min_value=1, native_max_value=SPEED_RANGE[1], entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[int], device.comfort_max_speed), + value_fn=lambda device: cast(int | None, device.comfort_max_speed), mode=NumberMode.BOX, ), BAFNumberDescription( @@ -61,7 +61,7 @@ AUTO_COMFORT_NUMBER_DESCRIPTIONS = ( native_min_value=SPEED_RANGE[0], native_max_value=SPEED_RANGE[1], entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[int], device.comfort_heat_assist_speed), + value_fn=lambda device: cast(int | None, device.comfort_heat_assist_speed), mode=NumberMode.BOX, ), ) @@ -74,7 +74,7 @@ FAN_NUMBER_DESCRIPTIONS = ( native_max_value=HALF_DAY_SECS, entity_category=EntityCategory.CONFIG, native_unit_of_measurement=UnitOfTime.SECONDS, - value_fn=lambda device: cast(Optional[int], device.return_to_auto_timeout), + value_fn=lambda device: cast(int | None, device.return_to_auto_timeout), mode=NumberMode.SLIDER, ), BAFNumberDescription( @@ -84,7 +84,7 @@ FAN_NUMBER_DESCRIPTIONS = ( native_max_value=ONE_DAY_SECS, entity_category=EntityCategory.CONFIG, native_unit_of_measurement=UnitOfTime.SECONDS, - value_fn=lambda device: cast(Optional[int], device.motion_sense_timeout), + value_fn=lambda device: cast(int | None, device.motion_sense_timeout), mode=NumberMode.SLIDER, ), ) @@ -97,9 +97,7 @@ LIGHT_NUMBER_DESCRIPTIONS = ( native_max_value=HALF_DAY_SECS, entity_category=EntityCategory.CONFIG, native_unit_of_measurement=UnitOfTime.SECONDS, - value_fn=lambda device: cast( - Optional[int], device.light_return_to_auto_timeout - ), + value_fn=lambda device: cast(int | None, device.light_return_to_auto_timeout), mode=NumberMode.SLIDER, ), BAFNumberDescription( @@ -109,7 +107,7 @@ LIGHT_NUMBER_DESCRIPTIONS = ( native_max_value=ONE_DAY_SECS, entity_category=EntityCategory.CONFIG, native_unit_of_measurement=UnitOfTime.SECONDS, - value_fn=lambda device: cast(Optional[int], device.light_auto_motion_timeout), + value_fn=lambda device: cast(int | None, device.light_auto_motion_timeout), mode=NumberMode.SLIDER, ), ) diff --git a/homeassistant/components/baf/sensor.py b/homeassistant/components/baf/sensor.py index 81b48ae59d7..950a746cddd 100644 --- a/homeassistant/components/baf/sensor.py +++ b/homeassistant/components/baf/sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from typing import Optional, cast +from typing import cast from aiobafi6 import Device @@ -46,7 +46,7 @@ AUTO_COMFORT_SENSORS = ( native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, - value_fn=lambda device: cast(Optional[float], device.temperature), + value_fn=lambda device: cast(float | None, device.temperature), ), ) @@ -57,7 +57,7 @@ DEFINED_ONLY_SENSORS = ( native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, - value_fn=lambda device: cast(Optional[float], device.humidity), + value_fn=lambda device: cast(float | None, device.humidity), ), ) @@ -68,7 +68,7 @@ FAN_SENSORS = ( native_unit_of_measurement=REVOLUTIONS_PER_MINUTE, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, - value_fn=lambda device: cast(Optional[int], device.current_rpm), + value_fn=lambda device: cast(int | None, device.current_rpm), ), BAFSensorDescription( key="target_rpm", @@ -76,21 +76,21 @@ FAN_SENSORS = ( native_unit_of_measurement=REVOLUTIONS_PER_MINUTE, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, - value_fn=lambda device: cast(Optional[int], device.target_rpm), + value_fn=lambda device: cast(int | None, device.target_rpm), ), BAFSensorDescription( key="wifi_ssid", name="WiFi SSID", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, - value_fn=lambda device: cast(Optional[int], device.wifi_ssid), + value_fn=lambda device: cast(int | None, device.wifi_ssid), ), BAFSensorDescription( key="ip_address", name="IP Address", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, - value_fn=lambda device: cast(Optional[str], device.ip_address), + value_fn=lambda device: cast(str | None, device.ip_address), ), ) diff --git a/homeassistant/components/baf/switch.py b/homeassistant/components/baf/switch.py index 44671e68458..50ee178f9b1 100644 --- a/homeassistant/components/baf/switch.py +++ b/homeassistant/components/baf/switch.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass -from typing import Any, Optional, cast +from typing import Any, cast from aiobafi6 import Device @@ -38,13 +38,13 @@ BASE_SWITCHES = [ key="legacy_ir_remote_enable", name="Legacy IR Remote", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.legacy_ir_remote_enable), + value_fn=lambda device: cast(bool | None, device.legacy_ir_remote_enable), ), BAFSwitchDescription( key="led_indicators_enable", name="Led Indicators", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.led_indicators_enable), + value_fn=lambda device: cast(bool | None, device.led_indicators_enable), ), ] @@ -53,7 +53,7 @@ AUTO_COMFORT_SWITCHES = [ key="comfort_heat_assist_enable", name="Auto Comfort Heat Assist", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.comfort_heat_assist_enable), + value_fn=lambda device: cast(bool | None, device.comfort_heat_assist_enable), ), ] @@ -62,31 +62,31 @@ FAN_SWITCHES = [ key="fan_beep_enable", name="Beep", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.fan_beep_enable), + value_fn=lambda device: cast(bool | None, device.fan_beep_enable), ), BAFSwitchDescription( key="eco_enable", name="Eco Mode", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.eco_enable), + value_fn=lambda device: cast(bool | None, device.eco_enable), ), BAFSwitchDescription( key="motion_sense_enable", name="Motion Sense", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.motion_sense_enable), + value_fn=lambda device: cast(bool | None, device.motion_sense_enable), ), BAFSwitchDescription( key="return_to_auto_enable", name="Return to Auto", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.return_to_auto_enable), + value_fn=lambda device: cast(bool | None, device.return_to_auto_enable), ), BAFSwitchDescription( key="whoosh_enable", name="Whoosh", # Not a configuration switch - value_fn=lambda device: cast(Optional[bool], device.whoosh_enable), + value_fn=lambda device: cast(bool | None, device.whoosh_enable), ), ] @@ -96,15 +96,13 @@ LIGHT_SWITCHES = [ key="light_dim_to_warm_enable", name="Dim to Warm", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast(Optional[bool], device.light_dim_to_warm_enable), + value_fn=lambda device: cast(bool | None, device.light_dim_to_warm_enable), ), BAFSwitchDescription( key="light_return_to_auto_enable", name="Light Return to Auto", entity_category=EntityCategory.CONFIG, - value_fn=lambda device: cast( - Optional[bool], device.light_return_to_auto_enable - ), + value_fn=lambda device: cast(bool | None, device.light_return_to_auto_enable), ), ] diff --git a/homeassistant/components/brunt/cover.py b/homeassistant/components/brunt/cover.py index 599008adc60..36ee89e0395 100644 --- a/homeassistant/components/brunt/cover.py +++ b/homeassistant/components/brunt/cover.py @@ -1,7 +1,7 @@ """Support for Brunt Blind Engine covers.""" from __future__ import annotations -from typing import Any, Optional +from typing import Any from aiohttp.client_exceptions import ClientResponseError from brunt import BruntClientAsync, Thing @@ -53,7 +53,7 @@ async def async_setup_entry( class BruntDevice( - CoordinatorEntity[DataUpdateCoordinator[dict[Optional[str], Thing]]], CoverEntity + CoordinatorEntity[DataUpdateCoordinator[dict[str | None, Thing]]], CoverEntity ): """ Representation of a Brunt cover device. diff --git a/homeassistant/components/bthome/binary_sensor.py b/homeassistant/components/bthome/binary_sensor.py index bbd77f271a4..ad36fe3644e 100644 --- a/homeassistant/components/bthome/binary_sensor.py +++ b/homeassistant/components/bthome/binary_sensor.py @@ -1,8 +1,6 @@ """Support for BTHome binary sensors.""" from __future__ import annotations -from typing import Optional - from bthome_ble import ( BinarySensorDeviceClass as BTHomeBinarySensorDeviceClass, SensorUpdate, @@ -188,7 +186,7 @@ async def async_setup_entry( class BTHomeBluetoothBinarySensorEntity( - PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[Optional[bool]]], + PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[bool | None]], BinarySensorEntity, ): """Representation of a BTHome binary sensor.""" diff --git a/homeassistant/components/camera/__init__.py b/homeassistant/components/camera/__init__.py index d80504df8fc..11e75c50cfc 100644 --- a/homeassistant/components/camera/__init__.py +++ b/homeassistant/components/camera/__init__.py @@ -12,7 +12,7 @@ from functools import partial import logging import os from random import SystemRandom -from typing import Any, Final, Optional, cast, final +from typing import Any, Final, cast, final from aiohttp import hdrs, web import async_timeout @@ -294,7 +294,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[Optional[str]]] +RtspToWebRtcProviderType = Callable[[str, str, str], Awaitable[str | None]] def async_register_rtsp_to_web_rtc_provider( diff --git a/homeassistant/components/canary/sensor.py b/homeassistant/components/canary/sensor.py index 0b77815ce42..90cb20a6c6c 100644 --- a/homeassistant/components/canary/sensor.py +++ b/homeassistant/components/canary/sensor.py @@ -1,7 +1,7 @@ """Support for Canary sensors.""" from __future__ import annotations -from typing import Final, Optional +from typing import Final from canary.model import Device, Location, SensorType @@ -20,9 +20,7 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DATA_COORDINATOR, DOMAIN, MANUFACTURER from .coordinator import CanaryDataUpdateCoordinator -SensorTypeItem = tuple[ - str, Optional[str], Optional[str], Optional[SensorDeviceClass], list[str] -] +SensorTypeItem = tuple[str, str | None, str | None, SensorDeviceClass | None, list[str]] SENSOR_VALUE_PRECISION: Final = 2 ATTR_AIR_QUALITY: Final = "air_quality" diff --git a/homeassistant/components/cast/helpers.py b/homeassistant/components/cast/helpers.py index bd921bfa686..8883f84eea4 100644 --- a/homeassistant/components/cast/helpers.py +++ b/homeassistant/components/cast/helpers.py @@ -5,7 +5,6 @@ import asyncio import configparser from dataclasses import dataclass import logging -from typing import Optional from urllib.parse import urlparse import aiohttp @@ -33,7 +32,7 @@ class ChromecastInfo: """ cast_info: CastInfo = attr.ib() - is_dynamic_group = attr.ib(type=Optional[bool], default=None) + is_dynamic_group = attr.ib(type=bool | None, default=None) @property def friendly_name(self) -> str: diff --git a/homeassistant/components/cert_expiry/__init__.py b/homeassistant/components/cert_expiry/__init__.py index 85f73532fed..5f6152b7bc7 100644 --- a/homeassistant/components/cert_expiry/__init__.py +++ b/homeassistant/components/cert_expiry/__init__.py @@ -3,7 +3,6 @@ from __future__ import annotations from datetime import datetime, timedelta import logging -from typing import Optional from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( @@ -60,7 +59,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) -class CertExpiryDataUpdateCoordinator(DataUpdateCoordinator[Optional[datetime]]): +class CertExpiryDataUpdateCoordinator(DataUpdateCoordinator[datetime | None]): """Class to manage fetching Cert Expiry data from single endpoint.""" def __init__(self, hass, host, port): diff --git a/homeassistant/components/kraken/sensor.py b/homeassistant/components/kraken/sensor.py index d37ecfea889..dc86fb73d9b 100644 --- a/homeassistant/components/kraken/sensor.py +++ b/homeassistant/components/kraken/sensor.py @@ -2,7 +2,6 @@ from __future__ import annotations import logging -from typing import Optional from homeassistant.components.sensor import SensorEntity, SensorStateClass from homeassistant.config_entries import ConfigEntry @@ -90,7 +89,7 @@ async def async_setup_entry( class KrakenSensor( - CoordinatorEntity[DataUpdateCoordinator[Optional[KrakenResponse]]], SensorEntity + CoordinatorEntity[DataUpdateCoordinator[KrakenResponse | None]], SensorEntity ): """Define a Kraken sensor.""" diff --git a/homeassistant/components/lovelace/dashboard.py b/homeassistant/components/lovelace/dashboard.py index 377ba33f171..ef47ea0b1fc 100644 --- a/homeassistant/components/lovelace/dashboard.py +++ b/homeassistant/components/lovelace/dashboard.py @@ -6,7 +6,7 @@ import logging import os from pathlib import Path import time -from typing import Optional, cast +from typing import cast import voluptuous as vol @@ -234,7 +234,7 @@ class DashboardsCollection(collection.StorageCollection): async def _async_load_data(self) -> dict | None: """Load the data.""" if (data := await self.store.async_load()) is None: - return cast(Optional[dict], data) + return cast(dict | None, data) updated = False @@ -246,7 +246,7 @@ class DashboardsCollection(collection.StorageCollection): if updated: await self.store.async_save(data) - return cast(Optional[dict], data) + return cast(dict | None, data) async def _process_create_data(self, data: dict) -> dict: """Validate the config is valid.""" diff --git a/homeassistant/components/lovelace/resources.py b/homeassistant/components/lovelace/resources.py index 7e7c670baf5..e6c4acfdf69 100644 --- a/homeassistant/components/lovelace/resources.py +++ b/homeassistant/components/lovelace/resources.py @@ -2,7 +2,7 @@ from __future__ import annotations import logging -from typing import Optional, cast +from typing import cast import uuid import voluptuous as vol @@ -71,7 +71,7 @@ class ResourceStorageCollection(collection.StorageCollection): async def _async_load_data(self) -> dict | None: """Load the data.""" if (data := await self.store.async_load()) is not None: - return cast(Optional[dict], data) + return cast(dict | None, data) # Import it from config. try: diff --git a/homeassistant/components/motioneye/media_source.py b/homeassistant/components/motioneye/media_source.py index 20fc4359ab2..46300e3d3db 100644 --- a/homeassistant/components/motioneye/media_source.py +++ b/homeassistant/components/motioneye/media_source.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging from pathlib import PurePath -from typing import Optional, cast +from typing import cast from motioneye_client.const import KEY_MEDIA_LIST, KEY_MIME_TYPE, KEY_PATH @@ -90,7 +90,7 @@ class MotionEyeMediaSource(MediaSource): base = [None] * 4 data = identifier.split("#", 3) return cast( - tuple[Optional[str], Optional[str], Optional[str], Optional[str]], + tuple[str | None, str | None, str | None, str | None], tuple(data + base)[:4], # type: ignore[operator] ) diff --git a/homeassistant/components/mysensors/remote.py b/homeassistant/components/mysensors/remote.py index de8774381c0..d72bbfa4235 100644 --- a/homeassistant/components/mysensors/remote.py +++ b/homeassistant/components/mysensors/remote.py @@ -2,7 +2,7 @@ from __future__ import annotations from collections.abc import Iterable -from typing import Any, Optional, cast +from typing import Any, cast from homeassistant.components.remote import ( ATTR_COMMAND, @@ -59,7 +59,7 @@ class MySensorsRemote(MySensorsEntity, RemoteEntity): def is_on(self) -> bool | None: """Return True if remote is on.""" set_req = self.gateway.const.SetReq - value = cast(Optional[str], self._child.values.get(set_req.V_LIGHT)) + value = cast(str | None, self._child.values.get(set_req.V_LIGHT)) if value is None: return None return value == "1" @@ -120,5 +120,5 @@ class MySensorsRemote(MySensorsEntity, RemoteEntity): """Update the controller with the latest value from a device.""" super()._async_update() self._current_command = cast( - Optional[str], self._child.values.get(self.value_type) + str | None, self._child.values.get(self.value_type) ) diff --git a/homeassistant/components/notify/legacy.py b/homeassistant/components/notify/legacy.py index a5d58451c5e..6046039aab1 100644 --- a/homeassistant/components/notify/legacy.py +++ b/homeassistant/components/notify/legacy.py @@ -4,7 +4,7 @@ from __future__ import annotations import asyncio from collections.abc import Callable, Coroutine from functools import partial -from typing import Any, Optional, Protocol, cast +from typing import Any, Protocol, cast from homeassistant.const import CONF_DESCRIPTION, CONF_NAME from homeassistant.core import HomeAssistant, ServiceCall, callback @@ -71,7 +71,7 @@ def async_setup_legacy( p_config = {} platform = cast( - Optional[LegacyNotifyPlatform], + LegacyNotifyPlatform | None, await async_prepare_setup_platform(hass, config, DOMAIN, integration_name), ) diff --git a/homeassistant/components/qingping/binary_sensor.py b/homeassistant/components/qingping/binary_sensor.py index b3cb80ad0f2..3a40e1baa09 100644 --- a/homeassistant/components/qingping/binary_sensor.py +++ b/homeassistant/components/qingping/binary_sensor.py @@ -1,8 +1,6 @@ """Support for Qingping binary sensors.""" from __future__ import annotations -from typing import Optional - from qingping_ble import ( BinarySensorDeviceClass as QingpingBinarySensorDeviceClass, SensorUpdate, @@ -93,7 +91,7 @@ async def async_setup_entry( class QingpingBluetoothSensorEntity( - PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[Optional[bool]]], + PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[bool | None]], BinarySensorEntity, ): """Representation of a Qingping binary sensor.""" diff --git a/homeassistant/components/renault/renault_coordinator.py b/homeassistant/components/renault/renault_coordinator.py index 22a98e0ab8e..d101b551dfe 100644 --- a/homeassistant/components/renault/renault_coordinator.py +++ b/homeassistant/components/renault/renault_coordinator.py @@ -5,7 +5,7 @@ import asyncio from collections.abc import Awaitable, Callable from datetime import timedelta import logging -from typing import Optional, TypeVar +from typing import TypeVar from renault_api.kamereon.exceptions import ( AccessDeniedException, @@ -17,7 +17,7 @@ from renault_api.kamereon.models import KamereonVehicleDataAttributes from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -T = TypeVar("T", bound=Optional[KamereonVehicleDataAttributes]) +T = TypeVar("T", bound=KamereonVehicleDataAttributes | None) # We have potentially 7 coordinators per vehicle _PARALLEL_SEMAPHORE = asyncio.Semaphore(1) diff --git a/homeassistant/components/sonos/__init__.py b/homeassistant/components/sonos/__init__.py index 095267072ac..f8047ba371f 100644 --- a/homeassistant/components/sonos/__init__.py +++ b/homeassistant/components/sonos/__init__.py @@ -8,7 +8,7 @@ import datetime from functools import partial import logging import socket -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from urllib.parse import urlparse from requests.exceptions import Timeout @@ -483,7 +483,7 @@ class SonosDiscoveryManager: uid, discovered_ip, "discovery", - boot_seqnum=cast(Optional[int], boot_seqnum), + boot_seqnum=cast(int | None, boot_seqnum), ) ) diff --git a/homeassistant/components/steam_online/sensor.py b/homeassistant/components/steam_online/sensor.py index 70225a90a1c..10e507775d0 100644 --- a/homeassistant/components/steam_online/sensor.py +++ b/homeassistant/components/steam_online/sensor.py @@ -3,7 +3,7 @@ from __future__ import annotations from datetime import datetime from time import localtime, mktime -from typing import Optional, cast +from typing import cast from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.config_entries import ConfigEntry @@ -79,7 +79,7 @@ class SteamSensor(SteamEntity, SensorEntity): attrs["game_icon"] = f"{STEAM_ICON_URL}{game_id}/{info}.jpg" self._attr_name = str(player["personaname"]) or None self._attr_entity_picture = str(player["avatarmedium"]) or None - if last_online := cast(Optional[int], player.get("lastlogoff")): + if last_online := cast(int | None, player.get("lastlogoff")): attrs["last_online"] = utc_from_timestamp(mktime(localtime(last_online))) if level := self.coordinator.data[self.entity_description.key]["level"]: attrs["level"] = level diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index b08487fc842..38aa6a4706e 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -11,7 +11,7 @@ import mimetypes import os from pathlib import Path import re -from typing import TYPE_CHECKING, Any, Optional, TypedDict, cast +from typing import TYPE_CHECKING, Any, TypedDict, cast from aiohttp import web import mutagen @@ -51,7 +51,7 @@ from .media_source import generate_media_source_id, media_source_id_to_kwargs _LOGGER = logging.getLogger(__name__) -TtsAudioType = tuple[Optional[str], Optional[bytes]] +TtsAudioType = tuple[str | None, bytes | None] ATTR_CACHE = "cache" ATTR_LANGUAGE = "language" diff --git a/homeassistant/components/wallbox/number.py b/homeassistant/components/wallbox/number.py index 04db0ad9f7c..50d8310eae3 100644 --- a/homeassistant/components/wallbox/number.py +++ b/homeassistant/components/wallbox/number.py @@ -2,7 +2,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Optional, cast +from typing import cast from homeassistant.components.number import NumberEntity, NumberEntityDescription from homeassistant.config_entries import ConfigEntry @@ -95,7 +95,7 @@ class WallboxNumber(WallboxEntity, NumberEntity): def native_value(self) -> float | None: """Return the value of the entity.""" return cast( - Optional[float], self._coordinator.data[CHARGER_MAX_CHARGING_CURRENT_KEY] + float | None, self._coordinator.data[CHARGER_MAX_CHARGING_CURRENT_KEY] ) async def async_set_native_value(self, value: float) -> None: diff --git a/homeassistant/components/wemo/__init__.py b/homeassistant/components/wemo/__init__.py index 2727c913fee..a70b5d70898 100644 --- a/homeassistant/components/wemo/__init__.py +++ b/homeassistant/components/wemo/__init__.py @@ -4,7 +4,6 @@ from __future__ import annotations from collections.abc import Sequence from datetime import datetime import logging -from typing import Optional import pywemo import voluptuous as vol @@ -43,7 +42,7 @@ WEMO_MODEL_DISPATCH = { _LOGGER = logging.getLogger(__name__) -HostPortTuple = tuple[str, Optional[int]] +HostPortTuple = tuple[str, int | None] def coerce_host_port(value: str) -> HostPortTuple: diff --git a/homeassistant/components/whois/sensor.py b/homeassistant/components/whois/sensor.py index 0fd51cc495e..9f4d7f07d52 100644 --- a/homeassistant/components/whois/sensor.py +++ b/homeassistant/components/whois/sensor.py @@ -4,7 +4,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timezone -from typing import Optional, cast +from typing import cast from whois import Domain @@ -155,7 +155,7 @@ async def async_setup_entry( class WhoisSensorEntity( - CoordinatorEntity[DataUpdateCoordinator[Optional[Domain]]], SensorEntity + CoordinatorEntity[DataUpdateCoordinator[Domain | None]], SensorEntity ): """Implementation of a WHOIS sensor.""" diff --git a/homeassistant/components/wiz/entity.py b/homeassistant/components/wiz/entity.py index 633fb71f165..67608db157a 100644 --- a/homeassistant/components/wiz/entity.py +++ b/homeassistant/components/wiz/entity.py @@ -2,7 +2,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import Any, Optional +from typing import Any from pywizlight.bulblibrary import BulbType @@ -18,7 +18,7 @@ from homeassistant.helpers.update_coordinator import ( from .models import WizData -class WizEntity(CoordinatorEntity[DataUpdateCoordinator[Optional[float]]], Entity): +class WizEntity(CoordinatorEntity[DataUpdateCoordinator[float | None]], Entity): """Representation of WiZ entity.""" _attr_has_entity_name = True diff --git a/homeassistant/components/wiz/number.py b/homeassistant/components/wiz/number.py index fc855e410fe..a57e4f4fd22 100644 --- a/homeassistant/components/wiz/number.py +++ b/homeassistant/components/wiz/number.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass -from typing import Optional, cast +from typing import cast from pywizlight import wizlight @@ -54,7 +54,7 @@ NUMBERS: tuple[WizNumberEntityDescription, ...] = ( native_step=1, icon="mdi:speedometer", name="Effect speed", - value_fn=lambda device: cast(Optional[int], device.state.get_speed()), + value_fn=lambda device: cast(int | None, device.state.get_speed()), set_value_fn=_async_set_speed, required_feature="effect", entity_category=EntityCategory.CONFIG, @@ -66,7 +66,7 @@ NUMBERS: tuple[WizNumberEntityDescription, ...] = ( native_step=1, icon="mdi:floor-lamp-dual", name="Dual head ratio", - value_fn=lambda device: cast(Optional[int], device.state.get_ratio()), + value_fn=lambda device: cast(int | None, device.state.get_ratio()), set_value_fn=_async_set_ratio, required_feature="dual_head", entity_category=EntityCategory.CONFIG, diff --git a/homeassistant/components/xiaomi_ble/binary_sensor.py b/homeassistant/components/xiaomi_ble/binary_sensor.py index 58d4787bd4a..1de3afff53f 100644 --- a/homeassistant/components/xiaomi_ble/binary_sensor.py +++ b/homeassistant/components/xiaomi_ble/binary_sensor.py @@ -1,8 +1,6 @@ """Support for Xiaomi binary sensors.""" from __future__ import annotations -from typing import Optional - from xiaomi_ble.parser import ( BinarySensorDeviceClass as XiaomiBinarySensorDeviceClass, ExtendedBinarySensorDeviceClass, @@ -121,7 +119,7 @@ async def async_setup_entry( class XiaomiBluetoothSensorEntity( - PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[Optional[bool]]], + PassiveBluetoothProcessorEntity[PassiveBluetoothDataProcessor[bool | None]], BinarySensorEntity, ): """Representation of a Xiaomi binary sensor.""" diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py index 553ef31bc2e..757841e0813 100644 --- a/homeassistant/config_entries.py +++ b/homeassistant/config_entries.py @@ -11,7 +11,7 @@ import functools import logging from random import randint from types import MappingProxyType, MethodType -from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast +from typing import TYPE_CHECKING, Any, TypeVar, cast import weakref from . import data_entry_flow, loader @@ -1437,7 +1437,7 @@ class ConfigFlow(data_entry_flow.FlowHandler): if not self.context: return None - return cast(Optional[str], self.context.get("unique_id")) + return cast(str | None, self.context.get("unique_id")) @staticmethod @callback diff --git a/homeassistant/core.py b/homeassistant/core.py index 8985119dd9d..97ffd3e7fe0 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -31,10 +31,8 @@ from typing import ( Any, Generic, NamedTuple, - Optional, ParamSpec, TypeVar, - Union, cast, overload, ) @@ -448,7 +446,7 @@ class HomeAssistant: # the type used for the cast. For history see: # https://github.com/home-assistant/core/pull/71960 if TYPE_CHECKING: - target = cast(Callable[..., Union[Coroutine[Any, Any, _R], _R]], target) + target = cast(Callable[..., Coroutine[Any, Any, _R] | _R], target) return self.async_add_hass_job(HassJob(target), *args) @overload @@ -626,7 +624,7 @@ class HomeAssistant: # the type used for the cast. For history see: # https://github.com/home-assistant/core/pull/71960 if TYPE_CHECKING: - target = cast(Callable[..., Union[Coroutine[Any, Any, _R], _R]], target) + target = cast(Callable[..., Coroutine[Any, Any, _R] | _R], target) return self.async_run_hass_job(HassJob(target), *args) def block_till_done(self) -> None: @@ -2011,13 +2009,13 @@ class Config: if time_zone is not None: self.set_time_zone(time_zone) if external_url is not _UNDEF: - self.external_url = cast(Optional[str], external_url) + self.external_url = cast(str | None, external_url) if internal_url is not _UNDEF: - self.internal_url = cast(Optional[str], internal_url) + self.internal_url = cast(str | None, internal_url) if currency is not None: self.currency = currency if country is not _UNDEF: - self.country = cast(Optional[str], country) + self.country = cast(str | None, country) if language is not None: self.language = language diff --git a/homeassistant/helpers/collection.py b/homeassistant/helpers/collection.py index 55be6dc7d27..437cd418719 100644 --- a/homeassistant/helpers/collection.py +++ b/homeassistant/helpers/collection.py @@ -7,7 +7,7 @@ from collections.abc import Awaitable, Callable, Coroutine, Iterable from dataclasses import dataclass from itertools import groupby import logging -from typing import Any, Optional, cast +from typing import Any, cast import voluptuous as vol from voluptuous.humanize import humanize_error @@ -238,7 +238,7 @@ class StorageCollection(ObservableCollection, ABC): async def _async_load_data(self) -> dict | None: """Load the data.""" - return cast(Optional[dict], await self.store.async_load()) + return cast(dict | None, await self.store.async_load()) async def async_load(self) -> None: """Load the storage Manager.""" diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index 56930a4784e..30181751f8c 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -10,7 +10,7 @@ import functools as ft import logging import re import sys -from typing import Any, Optional, cast +from typing import Any, cast from homeassistant.components import zone as zone_cmp from homeassistant.components.device_automation import condition as device_condition @@ -80,7 +80,7 @@ INPUT_ENTITY_ID = re.compile( r"^input_(?:select|text|number|boolean|datetime)\.(?!.+__)(?!_)[\da-z_]+(? TraceElement: diff --git a/homeassistant/helpers/significant_change.py b/homeassistant/helpers/significant_change.py index c1dbaf8c6e4..589d792f1f8 100644 --- a/homeassistant/helpers/significant_change.py +++ b/homeassistant/helpers/significant_change.py @@ -14,7 +14,7 @@ async def async_check_significant_change( new_state: str, new_attrs: dict, **kwargs, -) -> Optional[bool] +) -> bool | None ``` Return boolean to indicate if significantly changed. If don't know, return None. @@ -30,7 +30,7 @@ from __future__ import annotations from collections.abc import Callable from types import MappingProxyType -from typing import Any, Optional, Union +from typing import Any from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant, State, callback @@ -43,24 +43,24 @@ CheckTypeFunc = Callable[ [ HomeAssistant, str, - Union[dict, MappingProxyType], + dict | MappingProxyType, str, - Union[dict, MappingProxyType], + dict | MappingProxyType, ], - Optional[bool], + bool | None, ] ExtraCheckTypeFunc = Callable[ [ HomeAssistant, str, - Union[dict, MappingProxyType], + dict | MappingProxyType, Any, str, - Union[dict, MappingProxyType], + dict | MappingProxyType, Any, ], - Optional[bool], + bool | None, ]