Skip to content

Commit

Permalink
Use PEP 695 for function annotations (1) (home-assistant#117658)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored May 18, 2024
1 parent 900b621 commit 26a599a
Show file tree
Hide file tree
Showing 20 changed files with 43 additions and 89 deletions.
7 changes: 2 additions & 5 deletions homeassistant/components/august/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from datetime import datetime
from itertools import chain
import logging
from typing import Any, ParamSpec, TypeVar
from typing import Any

from aiohttp import ClientError, ClientResponseError
from yalexs.activity import ActivityTypes
Expand Down Expand Up @@ -36,9 +36,6 @@
from .subscriber import AugustSubscriberMixin
from .util import async_create_august_clientsession

_R = TypeVar("_R")
_P = ParamSpec("_P")

_LOGGER = logging.getLogger(__name__)

API_CACHED_ATTRS = {
Expand Down Expand Up @@ -403,7 +400,7 @@ async def async_unlock_async(self, device_id: str, hyper_bridge: bool) -> str:
hyper_bridge,
)

async def _async_call_api_op_requires_bridge(
async def _async_call_api_op_requires_bridge[**_P, _R](
self,
device_id: str,
func: Callable[_P, Coroutine[Any, Any, _R]],
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/counter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import logging
from typing import Any, Self, TypeVar
from typing import Any, Self

import voluptuous as vol

Expand All @@ -23,8 +23,6 @@
from homeassistant.helpers.storage import Store
from homeassistant.helpers.typing import ConfigType

_T = TypeVar("_T")

_LOGGER = logging.getLogger(__name__)

ATTR_INITIAL = "initial"
Expand Down Expand Up @@ -62,7 +60,7 @@
}


def _none_to_empty_dict(value: _T | None) -> _T | dict[str, Any]:
def _none_to_empty_dict[_T](value: _T | None) -> _T | dict[str, Any]:
if value is None:
return {}
return value
Expand Down
7 changes: 2 additions & 5 deletions homeassistant/components/cover/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import functools as ft
from functools import cached_property
import logging
from typing import Any, ParamSpec, TypeVar, final
from typing import Any, final

import voluptuous as vol

Expand Down Expand Up @@ -54,9 +54,6 @@

ENTITY_ID_FORMAT = DOMAIN + ".{}"

_P = ParamSpec("_P")
_R = TypeVar("_R")


class CoverDeviceClass(StrEnum):
"""Device class for cover."""
Expand Down Expand Up @@ -477,7 +474,7 @@ async def async_toggle_tilt(self, **kwargs: Any) -> None:
else:
await self.async_close_cover_tilt(**kwargs)

def _get_toggle_function(
def _get_toggle_function[**_P, _R](
self, fns: dict[str, Callable[_P, _R]]
) -> Callable[_P, _R]:
# If we are opening or closing and we support stopping, then we should stop
Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/diagnostics/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,24 @@
from __future__ import annotations

from collections.abc import Iterable, Mapping
from typing import Any, TypeVar, cast, overload
from typing import Any, cast, overload

from homeassistant.core import callback

from .const import REDACTED

_T = TypeVar("_T")


@overload
def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict: # type: ignore[overload-overlap]
...


@overload
def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T: ...
def async_redact_data[_T](data: _T, to_redact: Iterable[Any]) -> _T: ...


@callback
def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
def async_redact_data[_T](data: _T, to_redact: Iterable[Any]) -> _T:
"""Redact sensitive data in a dict."""
if not isinstance(data, (Mapping, list)):
return data
Expand Down
7 changes: 2 additions & 5 deletions homeassistant/components/fitbit/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABC, abstractmethod
from collections.abc import Callable
import logging
from typing import Any, TypeVar, cast
from typing import Any, cast

from fitbit import Fitbit
from fitbit.exceptions import HTTPException, HTTPUnauthorized
Expand All @@ -24,9 +24,6 @@
CONF_EXPIRES_AT = "expires_at"


_T = TypeVar("_T")


class FitbitApi(ABC):
"""Fitbit client library wrapper base class.
Expand Down Expand Up @@ -129,7 +126,7 @@ def _time_series() -> dict[str, Any]:
dated_results: list[dict[str, Any]] = response[key]
return dated_results[-1]

async def _run(self, func: Callable[[], _T]) -> _T:
async def _run[_T](self, func: Callable[[], _T]) -> _T:
"""Run client command."""
try:
return await self._hass.async_add_executor_job(func)
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/fronius/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import asyncio
from datetime import datetime, timedelta
import logging
from typing import Final, TypeVar
from typing import Final

from pyfronius import Fronius, FroniusError

Expand Down Expand Up @@ -39,8 +39,6 @@
_LOGGER: Final = logging.getLogger(__name__)
PLATFORMS: Final = [Platform.SENSOR]

_FroniusCoordinatorT = TypeVar("_FroniusCoordinatorT", bound=FroniusCoordinatorBase)

type FroniusConfigEntry = ConfigEntry[FroniusSolarNet]


Expand Down Expand Up @@ -255,7 +253,7 @@ async def _get_inverter_infos(self) -> list[FroniusDeviceInfo]:
return inverter_infos

@staticmethod
async def _init_optional_coordinator(
async def _init_optional_coordinator[_FroniusCoordinatorT: FroniusCoordinatorBase](
coordinator: _FroniusCoordinatorT,
) -> _FroniusCoordinatorT | None:
"""Initialize an update coordinator and return it if devices are found."""
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/google_assistant/trait.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
import logging
from typing import Any, TypeVar
from typing import Any

from homeassistant.components import (
alarm_control_panel,
Expand Down Expand Up @@ -242,10 +242,8 @@

FRIENDLY_DOMAIN = {cover.DOMAIN: "Cover", valve.DOMAIN: "Valve"}

_TraitT = TypeVar("_TraitT", bound="_Trait")


def register_trait(trait: type[_TraitT]) -> type[_TraitT]:
def register_trait[_TraitT: _Trait](trait: type[_TraitT]) -> type[_TraitT]:
"""Decorate a class to register a trait."""
TRAITS.append(trait)
return trait
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/history_stats/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from abc import abstractmethod
import datetime
from typing import Any, TypeVar
from typing import Any

import voluptuous as vol

Expand Down Expand Up @@ -55,10 +55,8 @@
}
ICON = "mdi:chart-line"

_T = TypeVar("_T", bound=dict[str, Any])


def exactly_two_period_keys(conf: _T) -> _T:
def exactly_two_period_keys[_T: dict[str, Any]](conf: _T) -> _T:
"""Ensure exactly 2 of CONF_PERIOD_KEYS are provided."""
if sum(param in conf for param in CONF_PERIOD_KEYS) != 2:
raise vol.Invalid(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections.abc import Callable
from datetime import timedelta
import logging
from typing import Any, TypeVar
from typing import Any

import voluptuous as vol

Expand Down Expand Up @@ -41,10 +41,8 @@
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
from homeassistant.helpers.typing import ConfigType

_T = TypeVar("_T", bound=dict[str, Any])


def validate_above_below(value: _T) -> _T:
def validate_above_below[_T: dict[str, Any]](value: _T) -> _T:
"""Validate that above and below can co-exist."""
above = value.get(CONF_ABOVE)
below = value.get(CONF_BELOW)
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/improv_ble/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import Any, TypeVar
from typing import Any

from bleak import BleakError
from improv_ble_client import (
Expand All @@ -30,8 +30,6 @@

_LOGGER = logging.getLogger(__name__)

_T = TypeVar("_T")

STEP_PROVISION_SCHEMA = vol.Schema(
{
vol.Required("ssid"): str,
Expand Down Expand Up @@ -392,7 +390,7 @@ def on_state_update(state: State) -> None:
return self.async_show_progress_done(next_step_id="provision")

@staticmethod
async def _try_call(func: Coroutine[Any, Any, _T]) -> _T:
async def _try_call[_T](func: Coroutine[Any, Any, _T]) -> _T:
"""Call the library and abort flow on common errors."""
try:
return await func
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/linear_garage_door/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import Any, TypeVar
from typing import Any

from linear_garage_door import Linear
from linear_garage_door.errors import InvalidLoginError
Expand All @@ -19,8 +19,6 @@

_LOGGER = logging.getLogger(__name__)

_T = TypeVar("_T")


@dataclass
class LinearDevice:
Expand Down Expand Up @@ -63,7 +61,7 @@ async def update_data(linear: Linear) -> dict[str, Any]:

return await self.execute(update_data)

async def execute(self, func: Callable[[Linear], Awaitable[_T]]) -> _T:
async def execute[_T](self, func: Callable[[Linear], Awaitable[_T]]) -> _T:
"""Execute an API call."""
linear = Linear()
try:
Expand Down
10 changes: 3 additions & 7 deletions homeassistant/components/melnor/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Melnor integration models."""

from collections.abc import Callable
from typing import TypeVar

from melnor_bluetooth.device import Device, Valve

Expand Down Expand Up @@ -77,14 +76,11 @@ def __init__(
)


T = TypeVar("T", bound=EntityDescription)


def get_entities_for_valves(
def get_entities_for_valves[_T: EntityDescription](
coordinator: MelnorDataUpdateCoordinator,
descriptions: list[T],
descriptions: list[_T],
function: Callable[
[Valve, T],
[Valve, _T],
CoordinatorEntity[MelnorDataUpdateCoordinator],
],
) -> list[CoordinatorEntity[MelnorDataUpdateCoordinator]]:
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/radiotherm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from collections.abc import Coroutine
from typing import Any, TypeVar
from typing import Any
from urllib.error import URLError

from radiotherm.validate import RadiothermTstatError
Expand All @@ -20,10 +20,8 @@

PLATFORMS: list[Platform] = [Platform.CLIMATE, Platform.SWITCH]

_T = TypeVar("_T")


async def _async_call_or_raise_not_ready(
async def _async_call_or_raise_not_ready[_T](
coro: Coroutine[Any, Any, _T], host: str
) -> _T:
"""Call a coro or raise ConfigEntryNotReady."""
Expand Down
10 changes: 4 additions & 6 deletions homeassistant/components/recorder/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import sqlite3
import threading
import time
from typing import TYPE_CHECKING, Any, TypeVar, cast
from typing import TYPE_CHECKING, Any, cast

import psutil_home_assistant as ha_psutil
from sqlalchemy import create_engine, event as sqlalchemy_event, exc, select, update
Expand Down Expand Up @@ -138,8 +138,6 @@

_LOGGER = logging.getLogger(__name__)

T = TypeVar("T")

DEFAULT_URL = "sqlite:///{hass_config_path}"

# Controls how often we clean up
Expand Down Expand Up @@ -366,9 +364,9 @@ def _async_commit(self, now: datetime) -> None:
self.queue_task(COMMIT_TASK)

@callback
def async_add_executor_job(
self, target: Callable[..., T], *args: Any
) -> asyncio.Future[T]:
def async_add_executor_job[_T](
self, target: Callable[..., _T], *args: Any
) -> asyncio.Future[_T]:
"""Add an executor job from within the event loop."""
return self.hass.loop.run_in_executor(self._db_executor, target, *args)

Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/rfxtrx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from collections.abc import Callable, Mapping
import copy
import logging
from typing import Any, NamedTuple, TypeVarTuple, cast
from typing import Any, NamedTuple, cast

import RFXtrx as rfxtrxmod
import voluptuous as vol
Expand Down Expand Up @@ -55,8 +55,6 @@
SIGNAL_EVENT = f"{DOMAIN}_event"
CONNECT_TIMEOUT = 30.0

_Ts = TypeVarTuple("_Ts")

_LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -573,7 +571,7 @@ def __init__(
"""Initialzie a switch or light device."""
super().__init__(device, device_id, event=event)

async def _async_send(
async def _async_send[*_Ts](
self, fun: Callable[[rfxtrxmod.PySerialTransport, *_Ts], None], *args: *_Ts
) -> None:
rfx_object: rfxtrxmod.Connect = self.hass.data[DOMAIN][DATA_RFXOBJECT]
Expand Down
Loading

0 comments on commit 26a599a

Please sign in to comment.