Add Self typing (1) [mypy 1.0] (#87598)

This commit is contained in:
Marc Mueller 2023-02-07 05:29:47 +01:00 committed by GitHub
parent a5d376069a
commit 342b406dc0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 23 additions and 35 deletions

View File

@ -2,17 +2,15 @@
from __future__ import annotations
from enum import Enum
from typing import Any, TypeVar
from typing import Any
_StrEnumSelfT = TypeVar("_StrEnumSelfT", bound="StrEnum")
from typing_extensions import Self
class StrEnum(str, Enum):
"""Partial backport of Python 3.11's StrEnum for our basic use cases."""
def __new__(
cls: type[_StrEnumSelfT], value: str, *args: Any, **kwargs: Any
) -> _StrEnumSelfT:
def __new__(cls, value: str, *args: Any, **kwargs: Any) -> Self:
"""Create a new StrEnum instance."""
if not isinstance(value, str):
raise TypeError(f"{value!r} is not a string")

View File

@ -3,10 +3,11 @@ from __future__ import annotations
from collections.abc import MutableMapping
from dataclasses import dataclass, field
from typing import TypeVar, cast
from typing import cast
from bleak.backends.service import BleakGATTServiceCollection
from lru import LRU # pylint: disable=no-name-in-module
from typing_extensions import Self
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
@ -19,8 +20,6 @@ from .entry_data import RuntimeEntryData
STORAGE_VERSION = 1
MAX_CACHED_SERVICES = 128
_DomainDataSelfT = TypeVar("_DomainDataSelfT", bound="DomainData")
@dataclass
class DomainData:
@ -94,10 +93,10 @@ class DomainData:
)
@classmethod
def get(cls: type[_DomainDataSelfT], hass: HomeAssistant) -> _DomainDataSelfT:
def get(cls, hass: HomeAssistant) -> Self:
"""Get the global DomainData instance stored in hass.data."""
# Don't use setdefault - this is a hot code path
if DOMAIN in hass.data:
return cast(_DomainDataSelfT, hass.data[DOMAIN])
return cast(Self, hass.data[DOMAIN])
ret = hass.data[DOMAIN] = cls()
return ret

View File

@ -5,7 +5,7 @@ from collections.abc import Callable
from datetime import datetime, timedelta
import logging
import time
from typing import Any, TypeVar, cast
from typing import Any, cast
import ciso8601
from fnvhash import fnv1a_32
@ -30,6 +30,7 @@ from sqlalchemy.dialects import mysql, oracle, postgresql, sqlite
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import aliased, declarative_base, relationship
from sqlalchemy.orm.session import Session
from typing_extensions import Self
from homeassistant.const import (
MAX_LENGTH_EVENT_CONTEXT_ID,
@ -57,8 +58,6 @@ Base = declarative_base()
SCHEMA_VERSION = 33
_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")
_LOGGER = logging.getLogger(__name__)
TABLE_EVENTS = "events"
@ -472,9 +471,7 @@ class StatisticsBase:
sum = Column(DOUBLE_TYPE)
@classmethod
def from_stats(
cls: type[_StatisticsBaseSelfT], metadata_id: int, stats: StatisticData
) -> _StatisticsBaseSelfT:
def from_stats(cls, metadata_id: int, stats: StatisticData) -> Self:
"""Create object from a statistics."""
return cls( # type: ignore[call-arg,misc]
metadata_id=metadata_id,
@ -576,7 +573,7 @@ class RecorderRuns(Base): # type: ignore[misc,valid-type]
return [row[0] for row in query]
def to_native(self, validate_entity_id: bool = True) -> RecorderRuns:
def to_native(self, validate_entity_id: bool = True) -> Self:
"""Return self, native format is this model."""
return self

View File

@ -14,6 +14,8 @@ from types import MappingProxyType, MethodType
from typing import TYPE_CHECKING, Any, TypeVar, cast
import weakref
from typing_extensions import Self
from . import data_entry_flow, loader
from .backports.enum import StrEnum
from .components import persistent_notification
@ -86,7 +88,6 @@ PATH_CONFIG = ".config_entries.json"
SAVE_DELAY = 1
_ConfigEntryStateSelfT = TypeVar("_ConfigEntryStateSelfT", bound="ConfigEntryState")
_R = TypeVar("_R")
@ -110,9 +111,7 @@ class ConfigEntryState(Enum):
_recoverable: bool
def __new__(
cls: type[_ConfigEntryStateSelfT], value: str, recoverable: bool
) -> _ConfigEntryStateSelfT:
def __new__(cls, value: str, recoverable: bool) -> Self:
"""Create new ConfigEntryState."""
obj = object.__new__(cls)
obj._value_ = value

View File

@ -37,6 +37,7 @@ from typing import (
)
from urllib.parse import urlparse
from typing_extensions import Self
import voluptuous as vol
import yarl
@ -1075,9 +1076,6 @@ class EventBus:
)
_StateT = TypeVar("_StateT", bound="State")
class State:
"""Object to represent a state within the state machine.
@ -1200,7 +1198,7 @@ class State:
return compressed_state
@classmethod
def from_dict(cls: type[_StateT], json_dict: dict[str, Any]) -> _StateT | None:
def from_dict(cls, json_dict: dict[str, Any]) -> Self | None:
"""Initialize a state from a dict.
Async friendly.

View File

@ -5,7 +5,9 @@ from abc import ABC, abstractmethod
import asyncio
from datetime import datetime, timedelta
import logging
from typing import Any, TypeVar, cast
from typing import Any, cast
from typing_extensions import Self
from homeassistant.const import ATTR_RESTORED, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant, State, callback, valid_entity_id
@ -32,8 +34,6 @@ STATE_DUMP_INTERVAL = timedelta(minutes=15)
# How long should a saved state be preserved if the entity no longer exists
STATE_EXPIRATION = timedelta(days=7)
_StoredStateSelfT = TypeVar("_StoredStateSelfT", bound="StoredState")
class ExtraStoredData(ABC):
"""Object to hold extra stored data."""
@ -82,7 +82,7 @@ class StoredState:
return result
@classmethod
def from_dict(cls: type[_StoredStateSelfT], json_dict: dict) -> _StoredStateSelfT:
def from_dict(cls, json_dict: dict) -> Self:
"""Initialize a stored state from a dict."""
extra_data_dict = json_dict.get("extra_data")
extra_data = RestoredExtraData(extra_data_dict) if extra_data_dict else None

View File

@ -8,7 +8,7 @@ from __future__ import annotations
from collections.abc import Callable
from datetime import datetime, timedelta
import logging
from typing import Any, TypedDict, TypeVar, cast, overload
from typing import Any, TypedDict, cast, overload
import ciso8601
from fnvhash import fnv1a_32
@ -33,6 +33,7 @@ from sqlalchemy.dialects import mysql, oracle, postgresql, sqlite
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import aliased, declarative_base, relationship
from sqlalchemy.orm.session import Session
from typing_extensions import Self
from homeassistant.components.recorder.const import SupportedDialect
from homeassistant.const import (
@ -62,8 +63,6 @@ Base = declarative_base()
SCHEMA_VERSION = 30
_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")
_LOGGER = logging.getLogger(__name__)
TABLE_EVENTS = "events"
@ -497,9 +496,7 @@ class StatisticsBase:
sum = Column(DOUBLE_TYPE)
@classmethod
def from_stats(
cls: type[_StatisticsBaseSelfT], metadata_id: int, stats: StatisticData
) -> _StatisticsBaseSelfT:
def from_stats(cls, metadata_id: int, stats: StatisticData) -> Self:
"""Create object from a statistics."""
return cls( # type: ignore[call-arg,misc]
metadata_id=metadata_id,