Update typing 07 (#48057)

This commit is contained in:
Marc Mueller 2021-03-18 08:02:55 +01:00 committed by GitHub
parent 08db262972
commit 9e1a6610dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 185 additions and 142 deletions

View File

@ -1,6 +1,8 @@
"""Platform for Garmin Connect integration.""" """Platform for Garmin Connect integration."""
from __future__ import annotations
import logging import logging
from typing import Any, Dict from typing import Any
from garminconnect import ( from garminconnect import (
GarminConnectAuthenticationError, GarminConnectAuthenticationError,
@ -136,7 +138,7 @@ class GarminConnectSensor(Entity):
return attributes return attributes
@property @property
def device_info(self) -> Dict[str, Any]: def device_info(self) -> dict[str, Any]:
"""Return device information.""" """Return device information."""
return { return {
"identifiers": {(DOMAIN, self._unique_id)}, "identifiers": {(DOMAIN, self._unique_id)},

View File

@ -1,6 +1,7 @@
"""Geolocation support for GDACS Feed.""" """Geolocation support for GDACS Feed."""
from __future__ import annotations
import logging import logging
from typing import Optional
from homeassistant.components.geo_location import GeolocationEvent from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.const import ( from homeassistant.const import (
@ -169,7 +170,7 @@ class GdacsEvent(GeolocationEvent):
self._version = feed_entry.version self._version = feed_entry.version
@property @property
def unique_id(self) -> Optional[str]: def unique_id(self) -> str | None:
"""Return a unique ID containing latitude/longitude and external id.""" """Return a unique ID containing latitude/longitude and external id."""
return f"{self._integration_id}_{self._external_id}" return f"{self._integration_id}_{self._external_id}"
@ -186,22 +187,22 @@ class GdacsEvent(GeolocationEvent):
return SOURCE return SOURCE
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return self._title return self._title
@property @property
def distance(self) -> Optional[float]: def distance(self) -> float | None:
"""Return distance value of this external event.""" """Return distance value of this external event."""
return self._distance return self._distance
@property @property
def latitude(self) -> Optional[float]: def latitude(self) -> float | None:
"""Return latitude value of this external event.""" """Return latitude value of this external event."""
return self._latitude return self._latitude
@property @property
def longitude(self) -> Optional[float]: def longitude(self) -> float | None:
"""Return longitude value of this external event.""" """Return longitude value of this external event."""
return self._longitude return self._longitude

View File

@ -1,6 +1,7 @@
"""Feed Entity Manager Sensor support for GDACS Feed.""" """Feed Entity Manager Sensor support for GDACS Feed."""
from __future__ import annotations
import logging import logging
from typing import Optional
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -109,12 +110,12 @@ class GdacsSensor(Entity):
return self._total return self._total
@property @property
def unique_id(self) -> Optional[str]: def unique_id(self) -> str | None:
"""Return a unique ID containing latitude/longitude.""" """Return a unique ID containing latitude/longitude."""
return self._config_unique_id return self._config_unique_id
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return f"GDACS ({self._config_title})" return f"GDACS ({self._config_title})"

View File

@ -1,7 +1,9 @@
"""Support for a Genius Hub system.""" """Support for a Genius Hub system."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any, Dict, Optional from typing import Any
import aiohttp import aiohttp
from geniushubclient import GeniusHub from geniushubclient import GeniusHub
@ -218,12 +220,12 @@ class GeniusEntity(Entity):
"""Set up a listener when this entity is added to HA.""" """Set up a listener when this entity is added to HA."""
self.async_on_remove(async_dispatcher_connect(self.hass, DOMAIN, self._refresh)) self.async_on_remove(async_dispatcher_connect(self.hass, DOMAIN, self._refresh))
async def _refresh(self, payload: Optional[dict] = None) -> None: async def _refresh(self, payload: dict | None = None) -> None:
"""Process any signals.""" """Process any signals."""
self.async_schedule_update_ha_state(force_refresh=True) self.async_schedule_update_ha_state(force_refresh=True)
@property @property
def unique_id(self) -> Optional[str]: def unique_id(self) -> str | None:
"""Return a unique ID.""" """Return a unique ID."""
return self._unique_id return self._unique_id
@ -250,7 +252,7 @@ class GeniusDevice(GeniusEntity):
self._last_comms = self._state_attr = None self._last_comms = self._state_attr = None
@property @property
def extra_state_attributes(self) -> Dict[str, Any]: def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes.""" """Return the device state attributes."""
attrs = {} attrs = {}
attrs["assigned_zone"] = self._device.data["assignedZones"][0]["name"] attrs["assigned_zone"] = self._device.data["assignedZones"][0]["name"]
@ -285,7 +287,7 @@ class GeniusZone(GeniusEntity):
self._zone = zone self._zone = zone
self._unique_id = f"{broker.hub_uid}_zone_{zone.id}" self._unique_id = f"{broker.hub_uid}_zone_{zone.id}"
async def _refresh(self, payload: Optional[dict] = None) -> None: async def _refresh(self, payload: dict | None = None) -> None:
"""Process any signals.""" """Process any signals."""
if payload is None: if payload is None:
self.async_schedule_update_ha_state(force_refresh=True) self.async_schedule_update_ha_state(force_refresh=True)
@ -317,7 +319,7 @@ class GeniusZone(GeniusEntity):
return self._zone.name return self._zone.name
@property @property
def extra_state_attributes(self) -> Dict[str, Any]: def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes.""" """Return the device state attributes."""
status = {k: v for k, v in self._zone.data.items() if k in GH_ZONE_ATTRS} status = {k: v for k, v in self._zone.data.items() if k in GH_ZONE_ATTRS}
return {"status": status} return {"status": status}
@ -333,7 +335,7 @@ class GeniusHeatingZone(GeniusZone):
self._max_temp = self._min_temp = self._supported_features = None self._max_temp = self._min_temp = self._supported_features = None
@property @property
def current_temperature(self) -> Optional[float]: def current_temperature(self) -> float | None:
"""Return the current temperature.""" """Return the current temperature."""
return self._zone.data.get("temperature") return self._zone.data.get("temperature")

View File

@ -1,5 +1,5 @@
"""Support for Genius Hub climate devices.""" """Support for Genius Hub climate devices."""
from typing import List, Optional from __future__ import annotations
from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import ( from homeassistant.components.climate.const import (
@ -67,12 +67,12 @@ class GeniusClimateZone(GeniusHeatingZone, ClimateEntity):
return GH_HVAC_TO_HA.get(self._zone.data["mode"], HVAC_MODE_HEAT) return GH_HVAC_TO_HA.get(self._zone.data["mode"], HVAC_MODE_HEAT)
@property @property
def hvac_modes(self) -> List[str]: def hvac_modes(self) -> list[str]:
"""Return the list of available hvac operation modes.""" """Return the list of available hvac operation modes."""
return list(HA_HVAC_TO_GH) return list(HA_HVAC_TO_GH)
@property @property
def hvac_action(self) -> Optional[str]: def hvac_action(self) -> str | None:
"""Return the current running hvac operation if supported.""" """Return the current running hvac operation if supported."""
if "_state" in self._zone.data: # only for v3 API if "_state" in self._zone.data: # only for v3 API
if not self._zone.data["_state"].get("bIsActive"): if not self._zone.data["_state"].get("bIsActive"):
@ -83,12 +83,12 @@ class GeniusClimateZone(GeniusHeatingZone, ClimateEntity):
return None return None
@property @property
def preset_mode(self) -> Optional[str]: def preset_mode(self) -> str | None:
"""Return the current preset mode, e.g., home, away, temp.""" """Return the current preset mode, e.g., home, away, temp."""
return GH_PRESET_TO_HA.get(self._zone.data["mode"]) return GH_PRESET_TO_HA.get(self._zone.data["mode"])
@property @property
def preset_modes(self) -> Optional[List[str]]: def preset_modes(self) -> list[str] | None:
"""Return a list of available preset modes.""" """Return a list of available preset modes."""
if "occupied" in self._zone.data: # if has a movement sensor if "occupied" in self._zone.data: # if has a movement sensor
return [PRESET_ACTIVITY, PRESET_BOOST] return [PRESET_ACTIVITY, PRESET_BOOST]

View File

@ -1,6 +1,8 @@
"""Support for Genius Hub sensor devices.""" """Support for Genius Hub sensor devices."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from typing import Any, Dict from typing import Any
from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE from homeassistant.const import DEVICE_CLASS_BATTERY, PERCENTAGE
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.typing import ConfigType, HomeAssistantType
@ -106,7 +108,7 @@ class GeniusIssue(GeniusEntity):
return len(self._issues) return len(self._issues)
@property @property
def extra_state_attributes(self) -> Dict[str, Any]: def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes.""" """Return the device state attributes."""
return {f"{self._level}_list": self._issues} return {f"{self._level}_list": self._issues}

View File

@ -1,5 +1,5 @@
"""Support for Genius Hub water_heater devices.""" """Support for Genius Hub water_heater devices."""
from typing import List from __future__ import annotations
from homeassistant.components.water_heater import ( from homeassistant.components.water_heater import (
SUPPORT_OPERATION_MODE, SUPPORT_OPERATION_MODE,
@ -61,7 +61,7 @@ class GeniusWaterHeater(GeniusHeatingZone, WaterHeaterEntity):
self._supported_features = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE self._supported_features = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE
@property @property
def operation_list(self) -> List[str]: def operation_list(self) -> list[str]:
"""Return the list of available operation modes.""" """Return the list of available operation modes."""
return list(HA_OPMODE_TO_GH) return list(HA_OPMODE_TO_GH)

View File

@ -1,7 +1,8 @@
"""Support for generic GeoJSON events.""" """Support for generic GeoJSON events."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Optional
from geojson_client.generic_feed import GenericFeedManager from geojson_client.generic_feed import GenericFeedManager
import voluptuous as vol import voluptuous as vol
@ -176,22 +177,22 @@ class GeoJsonLocationEvent(GeolocationEvent):
return SOURCE return SOURCE
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return self._name return self._name
@property @property
def distance(self) -> Optional[float]: def distance(self) -> float | None:
"""Return distance value of this external event.""" """Return distance value of this external event."""
return self._distance return self._distance
@property @property
def latitude(self) -> Optional[float]: def latitude(self) -> float | None:
"""Return latitude value of this external event.""" """Return latitude value of this external event."""
return self._latitude return self._latitude
@property @property
def longitude(self) -> Optional[float]: def longitude(self) -> float | None:
"""Return longitude value of this external event.""" """Return longitude value of this external event."""
return self._longitude return self._longitude

View File

@ -1,7 +1,8 @@
"""Support for Geolocation.""" """Support for Geolocation."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Optional
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.helpers.config_validation import ( # noqa: F401 from homeassistant.helpers.config_validation import ( # noqa: F401
@ -60,17 +61,17 @@ class GeolocationEvent(Entity):
raise NotImplementedError raise NotImplementedError
@property @property
def distance(self) -> Optional[float]: def distance(self) -> float | None:
"""Return distance value of this external event.""" """Return distance value of this external event."""
return None return None
@property @property
def latitude(self) -> Optional[float]: def latitude(self) -> float | None:
"""Return latitude value of this external event.""" """Return latitude value of this external event."""
return None return None
@property @property
def longitude(self) -> Optional[float]: def longitude(self) -> float | None:
"""Return longitude value of this external event.""" """Return longitude value of this external event."""
return None return None

View File

@ -1,6 +1,7 @@
"""Geolocation support for GeoNet NZ Quakes Feeds.""" """Geolocation support for GeoNet NZ Quakes Feeds."""
from __future__ import annotations
import logging import logging
from typing import Optional
from homeassistant.components.geo_location import GeolocationEvent from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.const import ( from homeassistant.const import (
@ -142,7 +143,7 @@ class GeonetnzQuakesEvent(GeolocationEvent):
self._time = feed_entry.time self._time = feed_entry.time
@property @property
def unique_id(self) -> Optional[str]: def unique_id(self) -> str | None:
"""Return a unique ID containing latitude/longitude and external id.""" """Return a unique ID containing latitude/longitude and external id."""
return f"{self._integration_id}_{self._external_id}" return f"{self._integration_id}_{self._external_id}"
@ -157,22 +158,22 @@ class GeonetnzQuakesEvent(GeolocationEvent):
return SOURCE return SOURCE
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return self._title return self._title
@property @property
def distance(self) -> Optional[float]: def distance(self) -> float | None:
"""Return distance value of this external event.""" """Return distance value of this external event."""
return self._distance return self._distance
@property @property
def latitude(self) -> Optional[float]: def latitude(self) -> float | None:
"""Return latitude value of this external event.""" """Return latitude value of this external event."""
return self._latitude return self._latitude
@property @property
def longitude(self) -> Optional[float]: def longitude(self) -> float | None:
"""Return longitude value of this external event.""" """Return longitude value of this external event."""
return self._longitude return self._longitude

View File

@ -1,6 +1,7 @@
"""Feed Entity Manager Sensor support for GeoNet NZ Quakes Feeds.""" """Feed Entity Manager Sensor support for GeoNet NZ Quakes Feeds."""
from __future__ import annotations
import logging import logging
from typing import Optional
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -115,7 +116,7 @@ class GeonetnzQuakesSensor(Entity):
return self._config_unique_id return self._config_unique_id
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return f"GeoNet NZ Quakes ({self._config_title})" return f"GeoNet NZ Quakes ({self._config_title})"

View File

@ -1,8 +1,9 @@
"""The GeoNet NZ Volcano integration.""" """The GeoNet NZ Volcano integration."""
from __future__ import annotations
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging import logging
from typing import Optional
from aio_geojson_geonetnz_volcano import GeonetnzVolcanoFeedManager from aio_geojson_geonetnz_volcano import GeonetnzVolcanoFeedManager
import voluptuous as vol import voluptuous as vol
@ -172,11 +173,11 @@ class GeonetnzVolcanoFeedEntityManager:
"""Get feed entry by external id.""" """Get feed entry by external id."""
return self._feed_manager.feed_entries.get(external_id) return self._feed_manager.feed_entries.get(external_id)
def last_update(self) -> Optional[datetime]: def last_update(self) -> datetime | None:
"""Return the last update of this feed.""" """Return the last update of this feed."""
return self._feed_manager.last_update return self._feed_manager.last_update
def last_update_successful(self) -> Optional[datetime]: def last_update_successful(self) -> datetime | None:
"""Return the last successful update of this feed.""" """Return the last successful update of this feed."""
return self._feed_manager.last_update_successful return self._feed_manager.last_update_successful

View File

@ -1,6 +1,7 @@
"""Feed Entity Manager Sensor support for GeoNet NZ Volcano Feeds.""" """Feed Entity Manager Sensor support for GeoNet NZ Volcano Feeds."""
from __future__ import annotations
import logging import logging
from typing import Optional
from homeassistant.const import ( from homeassistant.const import (
ATTR_ATTRIBUTION, ATTR_ATTRIBUTION,
@ -139,7 +140,7 @@ class GeonetnzVolcanoSensor(Entity):
return DEFAULT_ICON return DEFAULT_ICON
@property @property
def name(self) -> Optional[str]: def name(self) -> str | None:
"""Return the name of the entity.""" """Return the name of the entity."""
return f"Volcano {self._title}" return f"Volcano {self._title}"

View File

@ -1,7 +1,9 @@
"""Common code for GogoGate2 component.""" """Common code for GogoGate2 component."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Awaitable, Callable, NamedTuple, Optional from typing import Awaitable, Callable, NamedTuple
from gogogate2_api import AbstractGateApi, GogoGate2Api, ISmartGateApi from gogogate2_api import AbstractGateApi, GogoGate2Api, ISmartGateApi
from gogogate2_api.common import AbstractDoor, get_door_by_id from gogogate2_api.common import AbstractDoor, get_door_by_id
@ -30,8 +32,8 @@ class StateData(NamedTuple):
"""State data for a cover entity.""" """State data for a cover entity."""
config_unique_id: str config_unique_id: str
unique_id: Optional[str] unique_id: str | None
door: Optional[AbstractDoor] door: AbstractDoor | None
class DeviceDataUpdateCoordinator(DataUpdateCoordinator): class DeviceDataUpdateCoordinator(DataUpdateCoordinator):
@ -45,8 +47,8 @@ class DeviceDataUpdateCoordinator(DataUpdateCoordinator):
*, *,
name: str, name: str,
update_interval: timedelta, update_interval: timedelta,
update_method: Optional[Callable[[], Awaitable]] = None, update_method: Callable[[], Awaitable] | None = None,
request_refresh_debouncer: Optional[Debouncer] = None, request_refresh_debouncer: Debouncer | None = None,
): ):
"""Initialize the data update coordinator.""" """Initialize the data update coordinator."""
DataUpdateCoordinator.__init__( DataUpdateCoordinator.__init__(
@ -78,7 +80,7 @@ class GoGoGate2Entity(CoordinatorEntity):
self._unique_id = unique_id self._unique_id = unique_id
@property @property
def unique_id(self) -> Optional[str]: def unique_id(self) -> str | None:
"""Return a unique ID.""" """Return a unique ID."""
return self._unique_id return self._unique_id

View File

@ -1,6 +1,8 @@
"""Support for Gogogate2 garage Doors.""" """Support for Gogogate2 garage Doors."""
from __future__ import annotations
import logging import logging
from typing import Callable, List, Optional from typing import Callable
from gogogate2_api.common import AbstractDoor, DoorStatus, get_configured_doors from gogogate2_api.common import AbstractDoor, DoorStatus, get_configured_doors
@ -44,7 +46,7 @@ async def async_setup_platform(
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], Optional[bool]], None], async_add_entities: Callable[[list[Entity], bool | None], None],
) -> None: ) -> None:
"""Set up the config entry.""" """Set up the config entry."""
data_update_coordinator = get_data_update_coordinator(hass, config_entry) data_update_coordinator = get_data_update_coordinator(hass, config_entry)

View File

@ -1,6 +1,8 @@
"""Support for Gogogate2 garage Doors.""" """Support for Gogogate2 garage Doors."""
from __future__ import annotations
from itertools import chain from itertools import chain
from typing import Callable, List, Optional from typing import Callable
from gogogate2_api.common import AbstractDoor, get_configured_doors from gogogate2_api.common import AbstractDoor, get_configured_doors
@ -26,7 +28,7 @@ SENSOR_ID_WIRED = "WIRE"
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], Optional[bool]], None], async_add_entities: Callable[[list[Entity], bool | None], None],
) -> None: ) -> None:
"""Set up the config entry.""" """Set up the config entry."""
data_update_coordinator = get_data_update_coordinator(hass, config_entry) data_update_coordinator = get_data_update_coordinator(hass, config_entry)

View File

@ -1,6 +1,8 @@
"""Support for Actions on Google Assistant Smart Home Control.""" """Support for Actions on Google Assistant Smart Home Control."""
from __future__ import annotations
import logging import logging
from typing import Any, Dict from typing import Any
import voluptuous as vol import voluptuous as vol
@ -87,7 +89,7 @@ GOOGLE_ASSISTANT_SCHEMA = vol.All(
CONFIG_SCHEMA = vol.Schema({DOMAIN: GOOGLE_ASSISTANT_SCHEMA}, extra=vol.ALLOW_EXTRA) CONFIG_SCHEMA = vol.Schema({DOMAIN: GOOGLE_ASSISTANT_SCHEMA}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]): async def async_setup(hass: HomeAssistant, yaml_config: dict[str, Any]):
"""Activate Google Actions component.""" """Activate Google Actions component."""
config = yaml_config.get(DOMAIN, {}) config = yaml_config.get(DOMAIN, {})

View File

@ -1,10 +1,11 @@
"""Helper classes for Google Assistant integration.""" """Helper classes for Google Assistant integration."""
from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from asyncio import gather from asyncio import gather
from collections.abc import Mapping from collections.abc import Mapping
import logging import logging
import pprint import pprint
from typing import Dict, List, Optional, Tuple
from aiohttp.web import json_response from aiohttp.web import json_response
@ -44,7 +45,7 @@ _LOGGER = logging.getLogger(__name__)
async def _get_entity_and_device( async def _get_entity_and_device(
hass, entity_id hass, entity_id
) -> Optional[Tuple[RegistryEntry, DeviceEntry]]: ) -> tuple[RegistryEntry, DeviceEntry] | None:
"""Fetch the entity and device entries for a entity_id.""" """Fetch the entity and device entries for a entity_id."""
dev_reg, ent_reg = await gather( dev_reg, ent_reg = await gather(
hass.helpers.device_registry.async_get_registry(), hass.helpers.device_registry.async_get_registry(),
@ -58,7 +59,7 @@ async def _get_entity_and_device(
return entity_entry, device_entry return entity_entry, device_entry
async def _get_area(hass, entity_entry, device_entry) -> Optional[AreaEntry]: async def _get_area(hass, entity_entry, device_entry) -> AreaEntry | None:
"""Calculate the area for an entity.""" """Calculate the area for an entity."""
if entity_entry and entity_entry.area_id: if entity_entry and entity_entry.area_id:
area_id = entity_entry.area_id area_id = entity_entry.area_id
@ -71,7 +72,7 @@ async def _get_area(hass, entity_entry, device_entry) -> Optional[AreaEntry]:
return area_reg.areas.get(area_id) return area_reg.areas.get(area_id)
async def _get_device_info(device_entry) -> Optional[Dict[str, str]]: async def _get_device_info(device_entry) -> dict[str, str] | None:
"""Retrieve the device info for a device.""" """Retrieve the device info for a device."""
if not device_entry: if not device_entry:
return None return None
@ -344,7 +345,7 @@ class RequestData:
user_id: str, user_id: str,
source: str, source: str,
request_id: str, request_id: str,
devices: Optional[List[dict]], devices: list[dict] | None,
): ):
"""Initialize the request data.""" """Initialize the request data."""
self.config = config self.config = config
@ -578,7 +579,7 @@ def deep_update(target, source):
@callback @callback
def async_get_entities(hass, config) -> List[GoogleEntity]: def async_get_entities(hass, config) -> list[GoogleEntity]:
"""Return all entities that are supported by Google.""" """Return all entities that are supported by Google."""
entities = [] entities = []
for state in hass.states.async_all(): for state in hass.states.async_all():

View File

@ -1,6 +1,7 @@
"""Implement the Google Smart Home traits.""" """Implement the Google Smart Home traits."""
from __future__ import annotations
import logging import logging
from typing import List, Optional
from homeassistant.components import ( from homeassistant.components import (
alarm_control_panel, alarm_control_panel,
@ -153,7 +154,7 @@ def _google_temp_unit(units):
return "C" return "C"
def _next_selected(items: List[str], selected: Optional[str]) -> Optional[str]: def _next_selected(items: list[str], selected: str | None) -> str | None:
"""Return the next item in a item list starting at given value. """Return the next item in a item list starting at given value.
If selected is missing in items, None is returned If selected is missing in items, None is returned

View File

@ -1,9 +1,11 @@
"""Support for Google Cloud Pub/Sub.""" """Support for Google Cloud Pub/Sub."""
from __future__ import annotations
import datetime import datetime
import json import json
import logging import logging
import os import os
from typing import Any, Dict from typing import Any
from google.cloud import pubsub_v1 from google.cloud import pubsub_v1
import voluptuous as vol import voluptuous as vol
@ -37,7 +39,7 @@ CONFIG_SCHEMA = vol.Schema(
) )
def setup(hass: HomeAssistant, yaml_config: Dict[str, Any]): def setup(hass: HomeAssistant, yaml_config: dict[str, Any]):
"""Activate Google Pub/Sub component.""" """Activate Google Pub/Sub component."""
config = yaml_config[DOMAIN] config = yaml_config[DOMAIN]

View File

@ -1,7 +1,8 @@
"""Helper and wrapper classes for Gree module.""" """Helper and wrapper classes for Gree module."""
from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import List
from greeclimate.device import Device, DeviceInfo from greeclimate.device import Device, DeviceInfo
from greeclimate.discovery import Discovery from greeclimate.discovery import Discovery
@ -86,7 +87,7 @@ class DeviceHelper:
return device return device
@staticmethod @staticmethod
async def find_devices() -> List[DeviceInfo]: async def find_devices() -> list[DeviceInfo]:
"""Gather a list of device infos from the local network.""" """Gather a list of device infos from the local network."""
return await Discovery.search_devices() return await Discovery.search_devices()

View File

@ -1,6 +1,7 @@
"""Support for interface with a Gree climate systems.""" """Support for interface with a Gree climate systems."""
from __future__ import annotations
import logging import logging
from typing import List
from greeclimate.device import ( from greeclimate.device import (
FanSpeed, FanSpeed,
@ -234,7 +235,7 @@ class GreeClimateEntity(CoordinatorEntity, ClimateEntity):
self.async_write_ha_state() self.async_write_ha_state()
@property @property
def hvac_modes(self) -> List[str]: def hvac_modes(self) -> list[str]:
"""Return the HVAC modes support by the device.""" """Return the HVAC modes support by the device."""
modes = [*HVAC_MODES_REVERSE] modes = [*HVAC_MODES_REVERSE]
modes.append(HVAC_MODE_OFF) modes.append(HVAC_MODE_OFF)
@ -282,7 +283,7 @@ class GreeClimateEntity(CoordinatorEntity, ClimateEntity):
self.async_write_ha_state() self.async_write_ha_state()
@property @property
def preset_modes(self) -> List[str]: def preset_modes(self) -> list[str]:
"""Return the preset modes support by the device.""" """Return the preset modes support by the device."""
return PRESET_MODES return PRESET_MODES
@ -302,7 +303,7 @@ class GreeClimateEntity(CoordinatorEntity, ClimateEntity):
self.async_write_ha_state() self.async_write_ha_state()
@property @property
def fan_modes(self) -> List[str]: def fan_modes(self) -> list[str]:
"""Return the fan modes support by the device.""" """Return the fan modes support by the device."""
return [*FAN_MODES_REVERSE] return [*FAN_MODES_REVERSE]
@ -342,7 +343,7 @@ class GreeClimateEntity(CoordinatorEntity, ClimateEntity):
self.async_write_ha_state() self.async_write_ha_state()
@property @property
def swing_modes(self) -> List[str]: def swing_modes(self) -> list[str]:
"""Return the swing modes currently supported for this device.""" """Return the swing modes currently supported for this device."""
return SWING_MODES return SWING_MODES

View File

@ -1,5 +1,5 @@
"""Support for interface with a Gree climate systems.""" """Support for interface with a Gree climate systems."""
from typing import Optional from __future__ import annotations
from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
@ -38,7 +38,7 @@ class GreeSwitchEntity(CoordinatorEntity, SwitchEntity):
return f"{self._mac}-panel-light" return f"{self._mac}-panel-light"
@property @property
def icon(self) -> Optional[str]: def icon(self) -> str | None:
"""Return the icon for the device.""" """Return the icon for the device."""
return "mdi:lightbulb" return "mdi:lightbulb"

View File

@ -1,9 +1,11 @@
"""Provide the functionality to group entities.""" """Provide the functionality to group entities."""
from __future__ import annotations
from abc import abstractmethod from abc import abstractmethod
import asyncio import asyncio
from contextvars import ContextVar from contextvars import ContextVar
import logging import logging
from typing import Any, Dict, Iterable, List, Optional, Set, cast from typing import Any, Iterable, List, cast
import voluptuous as vol import voluptuous as vol
@ -91,16 +93,16 @@ CONFIG_SCHEMA = vol.Schema(
class GroupIntegrationRegistry: class GroupIntegrationRegistry:
"""Class to hold a registry of integrations.""" """Class to hold a registry of integrations."""
on_off_mapping: Dict[str, str] = {STATE_ON: STATE_OFF} on_off_mapping: dict[str, str] = {STATE_ON: STATE_OFF}
off_on_mapping: Dict[str, str] = {STATE_OFF: STATE_ON} off_on_mapping: dict[str, str] = {STATE_OFF: STATE_ON}
on_states_by_domain: Dict[str, Set] = {} on_states_by_domain: dict[str, set] = {}
exclude_domains: Set = set() exclude_domains: set = set()
def exclude_domain(self) -> None: def exclude_domain(self) -> None:
"""Exclude the current domain.""" """Exclude the current domain."""
self.exclude_domains.add(current_domain.get()) self.exclude_domains.add(current_domain.get())
def on_off_states(self, on_states: Set, off_state: str) -> None: def on_off_states(self, on_states: set, off_state: str) -> None:
"""Register on and off states for the current domain.""" """Register on and off states for the current domain."""
for on_state in on_states: for on_state in on_states:
if on_state not in self.on_off_mapping: if on_state not in self.on_off_mapping:
@ -128,12 +130,12 @@ def is_on(hass, entity_id):
@bind_hass @bind_hass
def expand_entity_ids(hass: HomeAssistantType, entity_ids: Iterable[Any]) -> List[str]: def expand_entity_ids(hass: HomeAssistantType, entity_ids: Iterable[Any]) -> list[str]:
"""Return entity_ids with group entity ids replaced by their members. """Return entity_ids with group entity ids replaced by their members.
Async friendly. Async friendly.
""" """
found_ids: List[str] = [] found_ids: list[str] = []
for entity_id in entity_ids: for entity_id in entity_ids:
if not isinstance(entity_id, str) or entity_id in ( if not isinstance(entity_id, str) or entity_id in (
ENTITY_MATCH_NONE, ENTITY_MATCH_NONE,
@ -171,8 +173,8 @@ def expand_entity_ids(hass: HomeAssistantType, entity_ids: Iterable[Any]) -> Lis
@bind_hass @bind_hass
def get_entity_ids( def get_entity_ids(
hass: HomeAssistantType, entity_id: str, domain_filter: Optional[str] = None hass: HomeAssistantType, entity_id: str, domain_filter: str | None = None
) -> List[str]: ) -> list[str]:
"""Get members of this group. """Get members of this group.
Async friendly. Async friendly.
@ -192,7 +194,7 @@ def get_entity_ids(
@bind_hass @bind_hass
def groups_with_entity(hass: HomeAssistantType, entity_id: str) -> List[str]: def groups_with_entity(hass: HomeAssistantType, entity_id: str) -> list[str]:
"""Get all groups that contain this entity. """Get all groups that contain this entity.
Async friendly. Async friendly.

View File

@ -1,5 +1,5 @@
"""This platform allows several cover to be grouped into one cover.""" """This platform allows several cover to be grouped into one cover."""
from typing import Dict, Optional, Set from __future__ import annotations
import voluptuous as vol import voluptuous as vol
@ -76,18 +76,18 @@ class CoverGroup(GroupEntity, CoverEntity):
self._is_closed = False self._is_closed = False
self._is_closing = False self._is_closing = False
self._is_opening = False self._is_opening = False
self._cover_position: Optional[int] = 100 self._cover_position: int | None = 100
self._tilt_position = None self._tilt_position = None
self._supported_features = 0 self._supported_features = 0
self._assumed_state = True self._assumed_state = True
self._entities = entities self._entities = entities
self._covers: Dict[str, Set[str]] = { self._covers: dict[str, set[str]] = {
KEY_OPEN_CLOSE: set(), KEY_OPEN_CLOSE: set(),
KEY_STOP: set(), KEY_STOP: set(),
KEY_POSITION: set(), KEY_POSITION: set(),
} }
self._tilts: Dict[str, Set[str]] = { self._tilts: dict[str, set[str]] = {
KEY_OPEN_CLOSE: set(), KEY_OPEN_CLOSE: set(),
KEY_STOP: set(), KEY_STOP: set(),
KEY_POSITION: set(), KEY_POSITION: set(),
@ -102,7 +102,7 @@ class CoverGroup(GroupEntity, CoverEntity):
async def async_update_supported_features( async def async_update_supported_features(
self, self,
entity_id: str, entity_id: str,
new_state: Optional[State], new_state: State | None,
update_state: bool = True, update_state: bool = True,
) -> None: ) -> None:
"""Update dictionaries with supported features.""" """Update dictionaries with supported features."""
@ -197,7 +197,7 @@ class CoverGroup(GroupEntity, CoverEntity):
return self._is_closing return self._is_closing
@property @property
def current_cover_position(self) -> Optional[int]: def current_cover_position(self) -> int | None:
"""Return current position for all covers.""" """Return current position for all covers."""
return self._cover_position return self._cover_position

View File

@ -1,8 +1,10 @@
"""This platform allows several lights to be grouped into one light.""" """This platform allows several lights to be grouped into one light."""
from __future__ import annotations
import asyncio import asyncio
from collections import Counter from collections import Counter
import itertools import itertools
from typing import Any, Callable, Iterator, List, Optional, Tuple, cast from typing import Any, Callable, Iterator, cast
import voluptuous as vol import voluptuous as vol
@ -78,21 +80,21 @@ async def async_setup_platform(
class LightGroup(GroupEntity, light.LightEntity): class LightGroup(GroupEntity, light.LightEntity):
"""Representation of a light group.""" """Representation of a light group."""
def __init__(self, name: str, entity_ids: List[str]) -> None: def __init__(self, name: str, entity_ids: list[str]) -> None:
"""Initialize a light group.""" """Initialize a light group."""
self._name = name self._name = name
self._entity_ids = entity_ids self._entity_ids = entity_ids
self._is_on = False self._is_on = False
self._available = False self._available = False
self._icon = "mdi:lightbulb-group" self._icon = "mdi:lightbulb-group"
self._brightness: Optional[int] = None self._brightness: int | None = None
self._hs_color: Optional[Tuple[float, float]] = None self._hs_color: tuple[float, float] | None = None
self._color_temp: Optional[int] = None self._color_temp: int | None = None
self._min_mireds: int = 154 self._min_mireds: int = 154
self._max_mireds: int = 500 self._max_mireds: int = 500
self._white_value: Optional[int] = None self._white_value: int | None = None
self._effect_list: Optional[List[str]] = None self._effect_list: list[str] | None = None
self._effect: Optional[str] = None self._effect: str | None = None
self._supported_features: int = 0 self._supported_features: int = 0
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
@ -136,17 +138,17 @@ class LightGroup(GroupEntity, light.LightEntity):
return self._icon return self._icon
@property @property
def brightness(self) -> Optional[int]: def brightness(self) -> int | None:
"""Return the brightness of this light group between 0..255.""" """Return the brightness of this light group between 0..255."""
return self._brightness return self._brightness
@property @property
def hs_color(self) -> Optional[Tuple[float, float]]: def hs_color(self) -> tuple[float, float] | None:
"""Return the HS color value [float, float].""" """Return the HS color value [float, float]."""
return self._hs_color return self._hs_color
@property @property
def color_temp(self) -> Optional[int]: def color_temp(self) -> int | None:
"""Return the CT color value in mireds.""" """Return the CT color value in mireds."""
return self._color_temp return self._color_temp
@ -161,17 +163,17 @@ class LightGroup(GroupEntity, light.LightEntity):
return self._max_mireds return self._max_mireds
@property @property
def white_value(self) -> Optional[int]: def white_value(self) -> int | None:
"""Return the white value of this light group between 0..255.""" """Return the white value of this light group between 0..255."""
return self._white_value return self._white_value
@property @property
def effect_list(self) -> Optional[List[str]]: def effect_list(self) -> list[str] | None:
"""Return the list of supported effects.""" """Return the list of supported effects."""
return self._effect_list return self._effect_list
@property @property
def effect(self) -> Optional[str]: def effect(self) -> str | None:
"""Return the current effect.""" """Return the current effect."""
return self._effect return self._effect
@ -288,7 +290,7 @@ class LightGroup(GroupEntity, light.LightEntity):
async def async_update(self): async def async_update(self):
"""Query all members and determine the light group state.""" """Query all members and determine the light group state."""
all_states = [self.hass.states.get(x) for x in self._entity_ids] all_states = [self.hass.states.get(x) for x in self._entity_ids]
states: List[State] = list(filter(None, all_states)) states: list[State] = list(filter(None, all_states))
on_states = [state for state in states if state.state == STATE_ON] on_states = [state for state in states if state.state == STATE_ON]
self._is_on = len(on_states) > 0 self._is_on = len(on_states) > 0
@ -331,7 +333,7 @@ class LightGroup(GroupEntity, light.LightEntity):
self._supported_features &= SUPPORT_GROUP_LIGHT self._supported_features &= SUPPORT_GROUP_LIGHT
def _find_state_attributes(states: List[State], key: str) -> Iterator[Any]: def _find_state_attributes(states: list[State], key: str) -> Iterator[Any]:
"""Find attributes with matching key from states.""" """Find attributes with matching key from states."""
for state in states: for state in states:
value = state.attributes.get(key) value = state.attributes.get(key)
@ -350,9 +352,9 @@ def _mean_tuple(*args):
def _reduce_attribute( def _reduce_attribute(
states: List[State], states: list[State],
key: str, key: str,
default: Optional[Any] = None, default: Any | None = None,
reduce: Callable[..., Any] = _mean_int, reduce: Callable[..., Any] = _mean_int,
) -> Any: ) -> Any:
"""Find the first attribute matching key from states. """Find the first attribute matching key from states.

View File

@ -1,5 +1,7 @@
"""Module that groups code required to handle state restore for component.""" """Module that groups code required to handle state restore for component."""
from typing import Any, Dict, Iterable, Optional from __future__ import annotations
from typing import Any, Iterable
from homeassistant.core import Context, State from homeassistant.core import Context, State
from homeassistant.helpers.state import async_reproduce_state from homeassistant.helpers.state import async_reproduce_state
@ -12,8 +14,8 @@ async def async_reproduce_states(
hass: HomeAssistantType, hass: HomeAssistantType,
states: Iterable[State], states: Iterable[State],
*, *,
context: Optional[Context] = None, context: Context | None = None,
reproduce_options: Optional[Dict[str, Any]] = None, reproduce_options: dict[str, Any] | None = None,
) -> None: ) -> None:
"""Reproduce component states.""" """Reproduce component states."""
states_copy = [] states_copy = []

View File

@ -1,9 +1,11 @@
"""Support for GTFS (Google/General Transport Format Schema).""" """Support for GTFS (Google/General Transport Format Schema)."""
from __future__ import annotations
import datetime import datetime
import logging import logging
import os import os
import threading import threading
from typing import Any, Callable, Optional from typing import Any, Callable
import pygtfs import pygtfs
from sqlalchemy.sql import text from sqlalchemy.sql import text
@ -484,7 +486,7 @@ def setup_platform(
hass: HomeAssistantType, hass: HomeAssistantType,
config: ConfigType, config: ConfigType,
add_entities: Callable[[list], None], add_entities: Callable[[list], None],
discovery_info: Optional[DiscoveryInfoType] = None, discovery_info: DiscoveryInfoType | None = None,
) -> None: ) -> None:
"""Set up the GTFS sensor.""" """Set up the GTFS sensor."""
gtfs_dir = hass.config.path(DEFAULT_PATH) gtfs_dir = hass.config.path(DEFAULT_PATH)
@ -523,7 +525,7 @@ class GTFSDepartureSensor(Entity):
def __init__( def __init__(
self, self,
gtfs: Any, gtfs: Any,
name: Optional[Any], name: Any | None,
origin: Any, origin: Any,
destination: Any, destination: Any,
offset: cv.time_period, offset: cv.time_period,
@ -540,7 +542,7 @@ class GTFSDepartureSensor(Entity):
self._available = False self._available = False
self._icon = ICON self._icon = ICON
self._name = "" self._name = ""
self._state: Optional[str] = None self._state: str | None = None
self._attributes = {} self._attributes = {}
self._agency = None self._agency = None
@ -559,7 +561,7 @@ class GTFSDepartureSensor(Entity):
return self._name return self._name
@property @property
def state(self) -> Optional[str]: # type: ignore def state(self) -> str | None: # type: ignore
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self._state return self._state
@ -811,7 +813,7 @@ class GTFSDepartureSensor(Entity):
col: getattr(resource, col) for col in resource.__table__.columns.keys() col: getattr(resource, col) for col in resource.__table__.columns.keys()
} }
def append_keys(self, resource: dict, prefix: Optional[str] = None) -> None: def append_keys(self, resource: dict, prefix: str | None = None) -> None:
"""Properly format key val pairs to append to attributes.""" """Properly format key val pairs to append to attributes."""
for attr, val in resource.items(): for attr, val in resource.items():
if val == "" or val is None or attr == "feed_id": if val == "" or val is None or attr == "feed_id":

View File

@ -1,6 +1,7 @@
"""The Elexa Guardian integration.""" """The Elexa Guardian integration."""
from __future__ import annotations
import asyncio import asyncio
from typing import Dict
from aioguardian import Client from aioguardian import Client
@ -314,7 +315,7 @@ class ValveControllerEntity(GuardianEntity):
def __init__( def __init__(
self, self,
entry: ConfigEntry, entry: ConfigEntry,
coordinators: Dict[str, DataUpdateCoordinator], coordinators: dict[str, DataUpdateCoordinator],
kind: str, kind: str,
name: str, name: str,
device_class: str, device_class: str,

View File

@ -1,5 +1,7 @@
"""Binary sensors for the Elexa Guardian integration.""" """Binary sensors for the Elexa Guardian integration."""
from typing import Callable, Dict, Optional from __future__ import annotations
from typing import Callable
from homeassistant.components.binary_sensor import ( from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_CONNECTIVITY,
@ -122,8 +124,8 @@ class PairedSensorBinarySensor(PairedSensorEntity, BinarySensorEntity):
coordinator: DataUpdateCoordinator, coordinator: DataUpdateCoordinator,
kind: str, kind: str,
name: str, name: str,
device_class: Optional[str], device_class: str | None,
icon: Optional[str], icon: str | None,
) -> None: ) -> None:
"""Initialize.""" """Initialize."""
super().__init__(entry, coordinator, kind, name, device_class, icon) super().__init__(entry, coordinator, kind, name, device_class, icon)
@ -155,11 +157,11 @@ class ValveControllerBinarySensor(ValveControllerEntity, BinarySensorEntity):
def __init__( def __init__(
self, self,
entry: ConfigEntry, entry: ConfigEntry,
coordinators: Dict[str, DataUpdateCoordinator], coordinators: dict[str, DataUpdateCoordinator],
kind: str, kind: str,
name: str, name: str,
device_class: Optional[str], device_class: str | None,
icon: Optional[str], icon: str | None,
) -> None: ) -> None:
"""Initialize.""" """Initialize."""
super().__init__(entry, coordinators, kind, name, device_class, icon) super().__init__(entry, coordinators, kind, name, device_class, icon)

View File

@ -1,5 +1,7 @@
"""Sensors for the Elexa Guardian integration.""" """Sensors for the Elexa Guardian integration."""
from typing import Callable, Dict, Optional from __future__ import annotations
from typing import Callable
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
@ -117,9 +119,9 @@ class PairedSensorSensor(PairedSensorEntity):
coordinator: DataUpdateCoordinator, coordinator: DataUpdateCoordinator,
kind: str, kind: str,
name: str, name: str,
device_class: Optional[str], device_class: str | None,
icon: Optional[str], icon: str | None,
unit: Optional[str], unit: str | None,
) -> None: ) -> None:
"""Initialize.""" """Initialize."""
super().__init__(entry, coordinator, kind, name, device_class, icon) super().__init__(entry, coordinator, kind, name, device_class, icon)
@ -157,12 +159,12 @@ class ValveControllerSensor(ValveControllerEntity):
def __init__( def __init__(
self, self,
entry: ConfigEntry, entry: ConfigEntry,
coordinators: Dict[str, DataUpdateCoordinator], coordinators: dict[str, DataUpdateCoordinator],
kind: str, kind: str,
name: str, name: str,
device_class: Optional[str], device_class: str | None,
icon: Optional[str], icon: str | None,
unit: Optional[str], unit: str | None,
) -> None: ) -> None:
"""Initialize.""" """Initialize."""
super().__init__(entry, coordinators, kind, name, device_class, icon) super().__init__(entry, coordinators, kind, name, device_class, icon)

View File

@ -1,5 +1,7 @@
"""Switches for the Elexa Guardian integration.""" """Switches for the Elexa Guardian integration."""
from typing import Callable, Dict from __future__ import annotations
from typing import Callable
from aioguardian import Client from aioguardian import Client
from aioguardian.errors import GuardianError from aioguardian.errors import GuardianError
@ -84,7 +86,7 @@ class ValveControllerSwitch(ValveControllerEntity, SwitchEntity):
self, self,
entry: ConfigEntry, entry: ConfigEntry,
client: Client, client: Client,
coordinators: Dict[str, DataUpdateCoordinator], coordinators: dict[str, DataUpdateCoordinator],
): ):
"""Initialize.""" """Initialize."""
super().__init__( super().__init__(