Skip to content

Commit

Permalink
Use PEP 695 for class annotations (3) (#117777)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored May 20, 2024
1 parent 8f0fb4d commit 7b27101
Show file tree
Hide file tree
Showing 11 changed files with 38 additions and 59 deletions.
19 changes: 7 additions & 12 deletions homeassistant/components/switchbee/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import Any, TypeVar
from typing import Any

from switchbee.api.central_unit import SwitchBeeDeviceOfflineError, SwitchBeeError
from switchbee.device import (
Expand All @@ -23,16 +23,6 @@
from .coordinator import SwitchBeeCoordinator
from .entity import SwitchBeeDeviceEntity

_DeviceTypeT = TypeVar(
"_DeviceTypeT",
bound=(
SwitchBeeTimedSwitch
| SwitchBeeGroupSwitch
| SwitchBeeSwitch
| SwitchBeeTimerSwitch
),
)


async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
Expand All @@ -55,7 +45,12 @@ async def async_setup_entry(
)


class SwitchBeeSwitchEntity(SwitchBeeDeviceEntity[_DeviceTypeT], SwitchEntity):
class SwitchBeeSwitchEntity[
_DeviceTypeT: SwitchBeeTimedSwitch
| SwitchBeeGroupSwitch
| SwitchBeeSwitch
| SwitchBeeTimerSwitch
](SwitchBeeDeviceEntity[_DeviceTypeT], SwitchEntity):
"""Representation of a Switchbee switch."""

def __init__(
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/synology_dsm/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections.abc import Awaitable, Callable, Coroutine
from datetime import timedelta
import logging
from typing import Any, Concatenate, TypeVar
from typing import Any, Concatenate

from synology_dsm.api.surveillance_station.camera import SynoCamera
from synology_dsm.exceptions import (
Expand All @@ -28,7 +28,6 @@
)

_LOGGER = logging.getLogger(__name__)
_DataT = TypeVar("_DataT")


def async_re_login_on_expired[_T: SynologyDSMUpdateCoordinator[Any], **_P, _R](
Expand Down Expand Up @@ -57,7 +56,7 @@ async def _async_wrap(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> _R:
return _async_wrap


class SynologyDSMUpdateCoordinator(DataUpdateCoordinator[_DataT]):
class SynologyDSMUpdateCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""DataUpdateCoordinator base class for synology_dsm."""

def __init__(
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/synology_dsm/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, TypeVar
from typing import Any

from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
Expand All @@ -16,8 +16,6 @@
SynologyDSMUpdateCoordinator,
)

_CoordinatorT = TypeVar("_CoordinatorT", bound=SynologyDSMUpdateCoordinator[Any])


@dataclass(frozen=True, kw_only=True)
class SynologyDSMEntityDescription(EntityDescription):
Expand All @@ -26,7 +24,9 @@ class SynologyDSMEntityDescription(EntityDescription):
api_key: str


class SynologyDSMBaseEntity(CoordinatorEntity[_CoordinatorT]):
class SynologyDSMBaseEntity[_CoordinatorT: SynologyDSMUpdateCoordinator[Any]](
CoordinatorEntity[_CoordinatorT]
):
"""Representation of a Synology NAS entry."""

entity_description: SynologyDSMEntityDescription
Expand Down
9 changes: 3 additions & 6 deletions homeassistant/components/tplink_omada/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import asyncio
from datetime import timedelta
import logging
from typing import Generic, TypeVar

from tplink_omada_client import OmadaSiteClient
from tplink_omada_client.exceptions import OmadaClientException
Expand All @@ -13,10 +12,8 @@

_LOGGER = logging.getLogger(__name__)

T = TypeVar("T")


class OmadaCoordinator(DataUpdateCoordinator[dict[str, T]], Generic[T]):
class OmadaCoordinator[_T](DataUpdateCoordinator[dict[str, _T]]):
"""Coordinator for synchronizing bulk Omada data."""

def __init__(
Expand All @@ -35,14 +32,14 @@ def __init__(
)
self.omada_client = omada_client

async def _async_update_data(self) -> dict[str, T]:
async def _async_update_data(self) -> dict[str, _T]:
"""Fetch data from API endpoint."""
try:
async with asyncio.timeout(10):
return await self.poll_update()
except OmadaClientException as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err

async def poll_update(self) -> dict[str, T]:
async def poll_update(self) -> dict[str, _T]:
"""Poll the current data from the controller."""
raise NotImplementedError("Update method not implemented")
8 changes: 3 additions & 5 deletions homeassistant/components/tplink_omada/entity.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Base entity definitions."""

from typing import Any, Generic, TypeVar
from typing import Any

from tplink_omada_client.devices import OmadaDevice

Expand All @@ -11,13 +11,11 @@
from .const import DOMAIN
from .coordinator import OmadaCoordinator

T = TypeVar("T", bound="OmadaCoordinator[Any]")


class OmadaDeviceEntity(CoordinatorEntity[T], Generic[T]):
class OmadaDeviceEntity[_T: OmadaCoordinator[Any]](CoordinatorEntity[_T]):
"""Common base class for all entities associated with Omada SDN Devices."""

def __init__(self, coordinator: T, device: OmadaDevice) -> None:
def __init__(self, coordinator: _T, device: OmadaDevice) -> None:
"""Initialize the device."""
super().__init__(coordinator)
self.device = device
Expand Down
7 changes: 2 additions & 5 deletions homeassistant/components/vera/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from collections import defaultdict
from collections.abc import Awaitable
import logging
from typing import Any, Generic, TypeVar
from typing import Any

import pyvera as veraApi
from requests.exceptions import RequestException
Expand Down Expand Up @@ -207,10 +207,7 @@ def map_special_case(instance_class: type, entity_type: Platform) -> Platform:
)


_DeviceTypeT = TypeVar("_DeviceTypeT", bound=veraApi.VeraDevice)


class VeraDevice(Generic[_DeviceTypeT], Entity):
class VeraDevice[_DeviceTypeT: veraApi.VeraDevice](Entity):
"""Representation of a Vera device entity."""

def __init__(
Expand Down
10 changes: 4 additions & 6 deletions homeassistant/components/withings/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from abc import abstractmethod
from datetime import date, datetime, timedelta
from typing import TYPE_CHECKING, TypeVar
from typing import TYPE_CHECKING

from aiowithings import (
Activity,
Expand All @@ -30,12 +30,10 @@
if TYPE_CHECKING:
from . import WithingsConfigEntry

_T = TypeVar("_T")

UPDATE_INTERVAL = timedelta(minutes=10)


class WithingsDataUpdateCoordinator(DataUpdateCoordinator[_T]):
class WithingsDataUpdateCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""Base coordinator."""

config_entry: WithingsConfigEntry
Expand Down Expand Up @@ -75,14 +73,14 @@ async def async_webhook_data_updated(
)
await self.async_request_refresh()

async def _async_update_data(self) -> _T:
async def _async_update_data(self) -> _DataT:
try:
return await self._internal_update_data()
except (WithingsUnauthorizedError, WithingsAuthenticationFailedError) as exc:
raise ConfigEntryAuthFailed from exc

@abstractmethod
async def _internal_update_data(self) -> _T:
async def _internal_update_data(self) -> _DataT:
"""Update coordinator data."""


Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/withings/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@

from __future__ import annotations

from typing import TypeVar
from typing import Any

from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN
from .coordinator import WithingsDataUpdateCoordinator

_T = TypeVar("_T", bound=WithingsDataUpdateCoordinator)


class WithingsEntity(CoordinatorEntity[_T]):
class WithingsEntity[_T: WithingsDataUpdateCoordinator[Any]](CoordinatorEntity[_T]):
"""Base class for withings entities."""

_attr_has_entity_name = True
Expand Down
11 changes: 5 additions & 6 deletions homeassistant/components/withings/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Generic, TypeVar
from typing import Any

from aiowithings import (
Activity,
Expand Down Expand Up @@ -767,11 +767,10 @@ def _async_add_workout_entities() -> None:
async_add_entities(entities)


_T = TypeVar("_T", bound=WithingsDataUpdateCoordinator)
_ED = TypeVar("_ED", bound=SensorEntityDescription)


class WithingsSensor(WithingsEntity[_T], SensorEntity, Generic[_T, _ED]):
class WithingsSensor[
_T: WithingsDataUpdateCoordinator[Any],
_ED: SensorEntityDescription,
](WithingsEntity[_T], SensorEntity):
"""Implementation of a Withings sensor."""

entity_description: _ED
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/xiaomi_ble/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections.abc import Callable, Coroutine
from logging import Logger
from typing import Any, TypeVar
from typing import Any

from xiaomi_ble import SensorUpdate, XiaomiBluetoothDeviceData

Expand All @@ -22,8 +22,6 @@

from .const import CONF_SLEEPY_DEVICE

_T = TypeVar("_T")


class XiaomiActiveBluetoothProcessorCoordinator(
ActiveBluetoothProcessorCoordinator[SensorUpdate]
Expand Down Expand Up @@ -72,7 +70,7 @@ def sleepy_device(self) -> bool:
return self.entry.data.get(CONF_SLEEPY_DEVICE, self.device_data.sleepy_device)


class XiaomiPassiveBluetoothDataProcessor(
class XiaomiPassiveBluetoothDataProcessor[_T](
PassiveBluetoothDataProcessor[_T, SensorUpdate]
):
"""Define a Xiaomi Bluetooth Passive Update Data Processor."""
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/xiaomi_miio/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from enum import Enum
from functools import partial
import logging
from typing import Any, TypeVar
from typing import Any

from construct.core import ChecksumError
from miio import Device, DeviceException
Expand All @@ -22,8 +22,6 @@

_LOGGER = logging.getLogger(__name__)

_T = TypeVar("_T", bound=DataUpdateCoordinator[Any])


class ConnectXiaomiDevice:
"""Class to async connect to a Xiaomi Device."""
Expand Down Expand Up @@ -109,7 +107,9 @@ def device_info(self) -> DeviceInfo:
return device_info


class XiaomiCoordinatedMiioEntity(CoordinatorEntity[_T]):
class XiaomiCoordinatedMiioEntity[_T: DataUpdateCoordinator[Any]](
CoordinatorEntity[_T]
):
"""Representation of a base a coordinated Xiaomi Miio Entity."""

_attr_has_entity_name = True
Expand Down

0 comments on commit 7b27101

Please sign in to comment.