Use PEP 695 for class annotations (1) (#117775)

This commit is contained in:
Marc Mueller 2024-05-20 10:42:57 +02:00 committed by GitHub
parent 3f15b44a11
commit b93312b62c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 48 additions and 85 deletions

View File

@ -1,7 +1,5 @@
"""The base entity for the A. O. Smith integration."""
from typing import TypeVar
from py_aosmith import AOSmithAPIClient
from py_aosmith.models import Device as AOSmithDevice
@ -11,12 +9,10 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import AOSmithEnergyCoordinator, AOSmithStatusCoordinator
_AOSmithCoordinatorT = TypeVar(
"_AOSmithCoordinatorT", bound=AOSmithStatusCoordinator | AOSmithEnergyCoordinator
)
class AOSmithEntity(CoordinatorEntity[_AOSmithCoordinatorT]):
class AOSmithEntity[
_AOSmithCoordinatorT: AOSmithStatusCoordinator | AOSmithEnergyCoordinator
](CoordinatorEntity[_AOSmithCoordinatorT]):
"""Base entity for A. O. Smith."""
_attr_has_entity_name = True

View File

@ -1,7 +1,6 @@
"""The BleBox devices integration."""
import logging
from typing import Generic, TypeVar
from blebox_uniapi.box import Box
from blebox_uniapi.error import Error
@ -38,8 +37,6 @@ PLATFORMS = [
PARALLEL_UPDATES = 0
_FeatureT = TypeVar("_FeatureT", bound=Feature)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up BleBox devices from a config entry."""
@ -80,7 +77,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return unload_ok
class BleBoxEntity(Entity, Generic[_FeatureT]):
class BleBoxEntity[_FeatureT: Feature](Entity):
"""Implements a common class for entities representing a BleBox feature."""
def __init__(self, feature: _FeatureT) -> None:

View File

@ -7,7 +7,7 @@ from __future__ import annotations
from collections.abc import Callable, Coroutine
import logging
from typing import Any, Generic, TypeVar
from typing import Any
from bleak import BleakError
from bluetooth_data_tools import monotonic_time_coarse
@ -21,12 +21,8 @@ from .passive_update_coordinator import PassiveBluetoothDataUpdateCoordinator
POLL_DEFAULT_COOLDOWN = 10
POLL_DEFAULT_IMMEDIATE = True
_T = TypeVar("_T")
class ActiveBluetoothDataUpdateCoordinator(
PassiveBluetoothDataUpdateCoordinator, Generic[_T]
):
class ActiveBluetoothDataUpdateCoordinator[_T](PassiveBluetoothDataUpdateCoordinator):
"""A coordinator that receives passive data from advertisements but can also poll.
Unlike the passive processor coordinator, this coordinator does call a parser

View File

@ -7,7 +7,7 @@ from __future__ import annotations
from collections.abc import Callable, Coroutine
import logging
from typing import Any, TypeVar
from typing import Any
from bleak import BleakError
from bluetooth_data_tools import monotonic_time_coarse
@ -21,10 +21,10 @@ from .passive_update_processor import PassiveBluetoothProcessorCoordinator
POLL_DEFAULT_COOLDOWN = 10
POLL_DEFAULT_IMMEDIATE = True
_DataT = TypeVar("_DataT")
class ActiveBluetoothProcessorCoordinator(PassiveBluetoothProcessorCoordinator[_DataT]):
class ActiveBluetoothProcessorCoordinator[_DataT](
PassiveBluetoothProcessorCoordinator[_DataT]
):
"""A processor coordinator that parses passive data.
Parses passive data from advertisements but can also poll.

View File

@ -6,7 +6,7 @@ from dataclasses import dataclass
from fnmatch import translate
from functools import lru_cache
import re
from typing import TYPE_CHECKING, Final, Generic, TypedDict, TypeVar
from typing import TYPE_CHECKING, Final, TypedDict
from lru import LRU
@ -148,10 +148,9 @@ class IntegrationMatcher:
return matched_domains
_T = TypeVar("_T", BluetoothMatcher, BluetoothCallbackMatcherWithCallback)
class BluetoothMatcherIndexBase(Generic[_T]):
class BluetoothMatcherIndexBase[
_T: (BluetoothMatcher, BluetoothCallbackMatcherWithCallback)
]:
"""Bluetooth matcher base for the bluetooth integration.
The indexer puts each matcher in the bucket that it is most

View File

@ -6,7 +6,7 @@ import dataclasses
from datetime import timedelta
from functools import cache
import logging
from typing import TYPE_CHECKING, Any, Generic, Self, TypedDict, TypeVar, cast
from typing import TYPE_CHECKING, Any, Self, TypedDict, cast
from habluetooth import BluetoothScanningMode
@ -43,9 +43,6 @@ STORAGE_VERSION = 1
STORAGE_SAVE_INTERVAL = timedelta(minutes=15)
PASSIVE_UPDATE_PROCESSOR = "passive_update_processor"
_T = TypeVar("_T")
_DataT = TypeVar("_DataT")
@dataclasses.dataclass(slots=True, frozen=True)
class PassiveBluetoothEntityKey:
@ -125,7 +122,7 @@ def serialize_entity_description(description: EntityDescription) -> dict[str, An
@dataclasses.dataclass(slots=True, frozen=False)
class PassiveBluetoothDataUpdate(Generic[_T]):
class PassiveBluetoothDataUpdate[_T]:
"""Generic bluetooth data."""
devices: dict[str | None, DeviceInfo] = dataclasses.field(default_factory=dict)
@ -277,9 +274,7 @@ async def async_setup(hass: HomeAssistant) -> None:
)
class PassiveBluetoothProcessorCoordinator(
Generic[_DataT], BasePassiveBluetoothCoordinator
):
class PassiveBluetoothProcessorCoordinator[_DataT](BasePassiveBluetoothCoordinator):
"""Passive bluetooth processor coordinator for bluetooth advertisements.
The coordinator is responsible for dispatching the bluetooth data,
@ -388,13 +383,7 @@ class PassiveBluetoothProcessorCoordinator(
processor.async_handle_update(update, was_available)
_PassiveBluetoothDataProcessorT = TypeVar(
"_PassiveBluetoothDataProcessorT",
bound="PassiveBluetoothDataProcessor[Any, Any]",
)
class PassiveBluetoothDataProcessor(Generic[_T, _DataT]):
class PassiveBluetoothDataProcessor[_T, _DataT]:
"""Passive bluetooth data processor for bluetooth advertisements.
The processor is responsible for keeping track of the bluetooth data
@ -609,7 +598,9 @@ class PassiveBluetoothDataProcessor(Generic[_T, _DataT]):
self.async_update_listeners(new_data, was_available, changed_entity_keys)
class PassiveBluetoothProcessorEntity(Entity, Generic[_PassiveBluetoothDataProcessorT]):
class PassiveBluetoothProcessorEntity[
_PassiveBluetoothDataProcessorT: PassiveBluetoothDataProcessor[Any, Any]
](Entity):
"""A class for entities using PassiveBluetoothDataProcessor."""
_attr_has_entity_name = True

View File

@ -2,7 +2,6 @@
from collections.abc import Callable
from logging import Logger
from typing import TypeVar
from bthome_ble import BTHomeBluetoothDeviceData, SensorUpdate
@ -19,8 +18,6 @@ from homeassistant.core import HomeAssistant
from .const import CONF_SLEEPY_DEVICE
_T = TypeVar("_T")
class BTHomePassiveBluetoothProcessorCoordinator(
PassiveBluetoothProcessorCoordinator[SensorUpdate]
@ -51,7 +48,7 @@ class BTHomePassiveBluetoothProcessorCoordinator(
return self.entry.data.get(CONF_SLEEPY_DEVICE, self.device_data.sleepy_device)
class BTHomePassiveBluetoothDataProcessor(
class BTHomePassiveBluetoothDataProcessor[_T](
PassiveBluetoothDataProcessor[_T, SensorUpdate]
):
"""Define a BTHome Bluetooth Passive Update Data Processor."""

View File

@ -6,7 +6,7 @@ import asyncio
from collections.abc import Callable, Coroutine
from http import HTTPStatus
import os
from typing import Any, Generic, TypeVar, cast
from typing import Any, cast
from aiohttp import web
import voluptuous as vol
@ -21,10 +21,10 @@ from homeassistant.util.yaml.loader import JSON_TYPE
from .const import ACTION_CREATE_UPDATE, ACTION_DELETE
_DataT = TypeVar("_DataT", dict[str, dict[str, Any]], list[dict[str, Any]])
class BaseEditConfigView(HomeAssistantView, Generic[_DataT]):
class BaseEditConfigView[_DataT: (dict[str, dict[str, Any]], list[dict[str, Any]])](
HomeAssistantView
):
"""Configure a Group endpoint."""
def __init__(

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from typing import Any, TypedDict, TypeVar, cast
from typing import Any, TypedDict, cast
from pydeconz.interfaces.groups import GroupHandler
from pydeconz.interfaces.lights import LightHandler
@ -86,8 +86,6 @@ XMAS_LIGHT_EFFECTS = [
"waves",
]
_LightDeviceT = TypeVar("_LightDeviceT", bound=Group | Light)
class SetStateAttributes(TypedDict, total=False):
"""Attributes available with set state call."""
@ -167,7 +165,9 @@ async def async_setup_entry(
)
class DeconzBaseLight(DeconzDevice[_LightDeviceT], LightEntity):
class DeconzBaseLight[_LightDeviceT: Group | Light](
DeconzDevice[_LightDeviceT], LightEntity
):
"""Representation of a deCONZ light."""
TYPE = DOMAIN

View File

@ -4,7 +4,7 @@ from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
from typing import Any
from pydeconz.gateway import DeconzSession
from pydeconz.interfaces.sensors import SensorResources
@ -25,18 +25,18 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .deconz_device import DeconzDevice
from .hub import DeconzHub
T = TypeVar("T", Presence, PydeconzSensorBase)
@dataclass(frozen=True, kw_only=True)
class DeconzNumberDescription(Generic[T], NumberEntityDescription):
class DeconzNumberDescription[_T: (Presence, PydeconzSensorBase)](
NumberEntityDescription
):
"""Class describing deCONZ number entities."""
instance_check: type[T]
instance_check: type[_T]
name_suffix: str
set_fn: Callable[[DeconzSession, str, int], Coroutine[Any, Any, dict[str, Any]]]
update_key: str
value_fn: Callable[[T], float | None]
value_fn: Callable[[_T], float | None]
ENTITY_DESCRIPTIONS: tuple[DeconzNumberDescription, ...] = (

View File

@ -1,14 +1,11 @@
"""Helper class to convert between Home Assistant and ESPHome enum values."""
from typing import Generic, TypeVar, overload
from typing import overload
from aioesphomeapi import APIIntEnum
_EnumT = TypeVar("_EnumT", bound=APIIntEnum)
_ValT = TypeVar("_ValT")
class EsphomeEnumMapper(Generic[_EnumT, _ValT]):
class EsphomeEnumMapper[_EnumT: APIIntEnum, _ValT]:
"""Helper class to convert between hass and esphome enum values."""
def __init__(self, mapping: dict[_EnumT, _ValT]) -> None:

View File

@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio
from functools import cached_property
import re
from typing import Generic, TypeVar
from haffmpeg.core import HAFFmpeg
from haffmpeg.tools import IMAGE_JPEG, FFVersion, ImageFrame
@ -29,8 +28,6 @@ from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
from homeassistant.util.signal_type import SignalType
_HAFFmpegT = TypeVar("_HAFFmpegT", bound=HAFFmpeg)
DOMAIN = "ffmpeg"
SERVICE_START = "start"
@ -179,7 +176,7 @@ class FFmpegManager:
return CONTENT_TYPE_MULTIPART.format("ffserver")
class FFmpegBase(Entity, Generic[_HAFFmpegT]):
class FFmpegBase[_HAFFmpegT: HAFFmpeg](Entity):
"""Interface object for FFmpeg."""
_attr_should_poll = False

View File

@ -2,7 +2,7 @@
from __future__ import annotations
from typing import Any, TypeVar
from typing import Any
from haffmpeg.core import HAFFmpeg
import haffmpeg.sensor as ffmpeg_sensor
@ -27,8 +27,6 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
_HAFFmpegT = TypeVar("_HAFFmpegT", bound=HAFFmpeg)
CONF_RESET = "reset"
CONF_CHANGES = "changes"
CONF_REPEAT_TIME = "repeat_time"
@ -70,7 +68,9 @@ async def async_setup_platform(
async_add_entities([entity])
class FFmpegBinarySensor(FFmpegBase[_HAFFmpegT], BinarySensorEntity):
class FFmpegBinarySensor[_HAFFmpegT: HAFFmpeg](
FFmpegBase[_HAFFmpegT], BinarySensorEntity
):
"""A binary sensor which use FFmpeg for noise detection."""
def __init__(self, ffmpeg: _HAFFmpegT, config: dict[str, Any]) -> None:

View File

@ -2,8 +2,6 @@
from __future__ import annotations
from typing import TypeVar
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
@ -15,17 +13,12 @@ from .coordinator import (
FlumeNotificationDataUpdateCoordinator,
)
_FlumeCoordinatorT = TypeVar(
"_FlumeCoordinatorT",
bound=(
FlumeDeviceDataUpdateCoordinator
| FlumeDeviceConnectionUpdateCoordinator
| FlumeNotificationDataUpdateCoordinator
),
)
class FlumeEntity(CoordinatorEntity[_FlumeCoordinatorT]):
class FlumeEntity[
_FlumeCoordinatorT: FlumeDeviceDataUpdateCoordinator
| FlumeDeviceConnectionUpdateCoordinator
| FlumeNotificationDataUpdateCoordinator
](CoordinatorEntity[_FlumeCoordinatorT]):
"""Base entity class."""
_attr_attribution = "Data provided by Flume API"