From ea4e2ab4aaeb1b1d7993621c1fc3cf65f504ec8d Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Tue, 7 Feb 2023 05:30:22 +0100 Subject: [PATCH] Add Self typing (4) [mypy 1.0] (#87601) --- homeassistant/components/sensor/__init__.py | 4 +++- homeassistant/components/stream/worker.py | 3 ++- homeassistant/components/template/binary_sensor.py | 3 ++- homeassistant/components/timer/__init__.py | 5 +++-- homeassistant/components/tuya/base.py | 5 +++-- homeassistant/components/utility_meter/sensor.py | 3 ++- homeassistant/components/yeelight/scanner.py | 3 ++- homeassistant/components/zone/__init__.py | 5 +++-- homeassistant/helpers/check_config.py | 3 ++- homeassistant/helpers/httpx_client.py | 3 ++- homeassistant/util/timeout.py | 14 ++++++++------ 11 files changed, 32 insertions(+), 19 deletions(-) diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index 08e6a8a0c90e..66da8fff5759 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -11,6 +11,8 @@ from math import floor, log10 import re from typing import Any, Final, cast, final +from typing_extensions import Self + from homeassistant.config_entries import ConfigEntry # pylint: disable=[hass-deprecated-import] @@ -767,7 +769,7 @@ class SensorExtraStoredData(ExtraStoredData): } @classmethod - def from_dict(cls, restored: dict[str, Any]) -> SensorExtraStoredData | None: + def from_dict(cls, restored: dict[str, Any]) -> Self | None: """Initialize a stored sensor state from a dict.""" try: native_value = restored["native_value"] diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index e6b570a34ad2..caa3d974d046 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -12,6 +12,7 @@ from typing import Any, cast import attr import av +from typing_extensions import Self from homeassistant.core import HomeAssistant @@ -399,7 +400,7 @@ class PeekIterator(Iterator): # A pointer to either _iterator or _buffer self._next = self._iterator.__next__ - def __iter__(self) -> Iterator: + def __iter__(self) -> Self: """Return an iterator.""" return self diff --git a/homeassistant/components/template/binary_sensor.py b/homeassistant/components/template/binary_sensor.py index 82cb39704dda..923b61678517 100644 --- a/homeassistant/components/template/binary_sensor.py +++ b/homeassistant/components/template/binary_sensor.py @@ -7,6 +7,7 @@ from functools import partial import logging from typing import Any +from typing_extensions import Self import voluptuous as vol from homeassistant.components.binary_sensor import ( @@ -473,7 +474,7 @@ class AutoOffExtraStoredData(ExtraStoredData): } @classmethod - def from_dict(cls, restored: dict[str, Any]) -> AutoOffExtraStoredData | None: + def from_dict(cls, restored: dict[str, Any]) -> Self | None: """Initialize a stored binary sensor state from a dict.""" try: auto_off_time = restored["auto_off_time"] diff --git a/homeassistant/components/timer/__init__.py b/homeassistant/components/timer/__init__.py index 6b141ccea4c7..62d962ee526d 100644 --- a/homeassistant/components/timer/__init__.py +++ b/homeassistant/components/timer/__init__.py @@ -5,6 +5,7 @@ from collections.abc import Callable from datetime import datetime, timedelta import logging +from typing_extensions import Self import voluptuous as vol from homeassistant.const import ( @@ -207,14 +208,14 @@ class Timer(collection.CollectionEntity, RestoreEntity): self._attr_force_update = True @classmethod - def from_storage(cls, config: ConfigType) -> Timer: + def from_storage(cls, config: ConfigType) -> Self: """Return entity instance initialized from storage.""" timer = cls(config) timer.editable = True return timer @classmethod - def from_yaml(cls, config: ConfigType) -> Timer: + def from_yaml(cls, config: ConfigType) -> Self: """Return entity instance initialized from yaml.""" timer = cls(config) timer.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID]) diff --git a/homeassistant/components/tuya/base.py b/homeassistant/components/tuya/base.py index f27101e373d4..2658f50edad9 100644 --- a/homeassistant/components/tuya/base.py +++ b/homeassistant/components/tuya/base.py @@ -8,6 +8,7 @@ import struct from typing import Any, Literal, overload from tuya_iot import TuyaDevice, TuyaDeviceManager +from typing_extensions import Self from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo, Entity @@ -112,12 +113,12 @@ class ElectricityTypeData: voltage: str | None = None @classmethod - def from_json(cls, data: str) -> ElectricityTypeData: + def from_json(cls, data: str) -> Self: """Load JSON string and return a ElectricityTypeData object.""" return cls(**json.loads(data.lower())) @classmethod - def from_raw(cls, data: str) -> ElectricityTypeData: + def from_raw(cls, data: str) -> Self: """Decode base64 string and return a ElectricityTypeData object.""" raw = base64.b64decode(data) voltage = struct.unpack(">H", raw[0:2])[0] / 10.0 diff --git a/homeassistant/components/utility_meter/sensor.py b/homeassistant/components/utility_meter/sensor.py index 04909c1b7aed..066a3cd6e104 100644 --- a/homeassistant/components/utility_meter/sensor.py +++ b/homeassistant/components/utility_meter/sensor.py @@ -8,6 +8,7 @@ import logging from typing import Any from croniter import croniter +from typing_extensions import Self import voluptuous as vol from homeassistant.components.sensor import ( @@ -274,7 +275,7 @@ class UtilitySensorExtraStoredData(SensorExtraStoredData): return data @classmethod - def from_dict(cls, restored: dict[str, Any]) -> UtilitySensorExtraStoredData | None: + def from_dict(cls, restored: dict[str, Any]) -> Self | None: """Initialize a stored sensor state from a dict.""" extra = SensorExtraStoredData.from_dict(restored) if extra is None: diff --git a/homeassistant/components/yeelight/scanner.py b/homeassistant/components/yeelight/scanner.py index d988dfbcc41c..f6d2d7fde78b 100644 --- a/homeassistant/components/yeelight/scanner.py +++ b/homeassistant/components/yeelight/scanner.py @@ -12,6 +12,7 @@ from urllib.parse import urlparse import async_timeout from async_upnp_client.search import SsdpSearchListener from async_upnp_client.utils import CaseInsensitiveDict +from typing_extensions import Self from homeassistant import config_entries from homeassistant.components import network, ssdp @@ -35,7 +36,7 @@ _LOGGER = logging.getLogger(__name__) class YeelightScanner: """Scan for Yeelight devices.""" - _scanner: YeelightScanner | None = None + _scanner: Self | None = None @classmethod @callback diff --git a/homeassistant/components/zone/__init__.py b/homeassistant/components/zone/__init__.py index 816d8a62f181..3ab2a35bf1ea 100644 --- a/homeassistant/components/zone/__init__.py +++ b/homeassistant/components/zone/__init__.py @@ -5,6 +5,7 @@ from collections.abc import Callable import logging from typing import Any, cast +from typing_extensions import Self import voluptuous as vol from homeassistant import config_entries @@ -297,7 +298,7 @@ class Zone(collection.CollectionEntity): self._persons_in_zone: set[str] = set() @classmethod - def from_storage(cls, config: ConfigType) -> Zone: + def from_storage(cls, config: ConfigType) -> Self: """Return entity instance initialized from storage.""" zone = cls(config) zone.editable = True @@ -305,7 +306,7 @@ class Zone(collection.CollectionEntity): return zone @classmethod - def from_yaml(cls, config: ConfigType) -> Zone: + def from_yaml(cls, config: ConfigType) -> Self: """Return entity instance initialized from yaml.""" zone = cls(config) zone.editable = False diff --git a/homeassistant/helpers/check_config.py b/homeassistant/helpers/check_config.py index bc17330f656f..4cf689e47670 100644 --- a/homeassistant/helpers/check_config.py +++ b/homeassistant/helpers/check_config.py @@ -7,6 +7,7 @@ import os from pathlib import Path from typing import NamedTuple +from typing_extensions import Self import voluptuous as vol from homeassistant import loader @@ -54,7 +55,7 @@ class HomeAssistantConfig(OrderedDict): message: str, domain: str | None = None, config: ConfigType | None = None, - ) -> HomeAssistantConfig: + ) -> Self: """Add a single error.""" self.errors.append(CheckConfigError(str(message), domain, config)) return self diff --git a/homeassistant/helpers/httpx_client.py b/homeassistant/helpers/httpx_client.py index b932a1cd7952..e02759b09f8f 100644 --- a/homeassistant/helpers/httpx_client.py +++ b/homeassistant/helpers/httpx_client.py @@ -6,6 +6,7 @@ import sys from typing import Any import httpx +from typing_extensions import Self from homeassistant.const import APPLICATION_NAME, EVENT_HOMEASSISTANT_CLOSE, __version__ from homeassistant.core import Event, HomeAssistant, callback @@ -41,7 +42,7 @@ def get_async_client(hass: HomeAssistant, verify_ssl: bool = True) -> httpx.Asyn class HassHttpXAsyncClient(httpx.AsyncClient): """httpx AsyncClient that suppresses context management.""" - async def __aenter__(self: HassHttpXAsyncClient) -> HassHttpXAsyncClient: + async def __aenter__(self) -> Self: """Prevent an integration from reopen of the client via context manager.""" return self diff --git a/homeassistant/util/timeout.py b/homeassistant/util/timeout.py index 5821f89659e7..b92985016999 100644 --- a/homeassistant/util/timeout.py +++ b/homeassistant/util/timeout.py @@ -10,6 +10,8 @@ import enum from types import TracebackType from typing import Any +from typing_extensions import Self + from .async_ import run_callback_threadsafe ZONE_GLOBAL = "global" @@ -32,7 +34,7 @@ class _GlobalFreezeContext: self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() self._manager: TimeoutManager = manager - async def __aenter__(self) -> _GlobalFreezeContext: + async def __aenter__(self) -> Self: self._enter() return self @@ -45,7 +47,7 @@ class _GlobalFreezeContext: self._exit() return None - def __enter__(self) -> _GlobalFreezeContext: + def __enter__(self) -> Self: self._loop.call_soon_threadsafe(self._enter) return self @@ -100,7 +102,7 @@ class _ZoneFreezeContext: self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() self._zone: _ZoneTimeoutManager = zone - async def __aenter__(self) -> _ZoneFreezeContext: + async def __aenter__(self) -> Self: self._enter() return self @@ -113,7 +115,7 @@ class _ZoneFreezeContext: self._exit() return None - def __enter__(self) -> _ZoneFreezeContext: + def __enter__(self) -> Self: self._loop.call_soon_threadsafe(self._enter) return self @@ -161,7 +163,7 @@ class _GlobalTaskContext: self._state: _State = _State.INIT self._cool_down: float = cool_down - async def __aenter__(self) -> _GlobalTaskContext: + async def __aenter__(self) -> Self: self._manager.global_tasks.append(self) self._start_timer() self._state = _State.ACTIVE @@ -271,7 +273,7 @@ class _ZoneTaskContext: """Return state of the Zone task.""" return self._state - async def __aenter__(self) -> _ZoneTaskContext: + async def __aenter__(self) -> Self: self._zone.enter_task(self) self._state = _State.ACTIVE