Skip to content

Commit

Permalink
Add Self typing (1) [mypy 1.0] (home-assistant#87598)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored Feb 7, 2023
1 parent a5d3760 commit 342b406
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 35 deletions.
8 changes: 3 additions & 5 deletions homeassistant/backports/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
9 changes: 4 additions & 5 deletions homeassistant/components/esphome/domain_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@

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
Expand All @@ -19,8 +20,6 @@
STORAGE_VERSION = 1
MAX_CACHED_SERVICES = 128

_DomainDataSelfT = TypeVar("_DomainDataSelfT", bound="DomainData")


@dataclass
class DomainData:
Expand Down Expand Up @@ -94,10 +93,10 @@ def get_or_create_store(self, hass: HomeAssistant, entry: ConfigEntry) -> Store:
)

@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
11 changes: 4 additions & 7 deletions homeassistant/components/recorder/db_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
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
Expand All @@ -30,6 +30,7 @@
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,
Expand Down Expand Up @@ -57,8 +58,6 @@

SCHEMA_VERSION = 33

_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")

_LOGGER = logging.getLogger(__name__)

TABLE_EVENTS = "events"
Expand Down Expand Up @@ -472,9 +471,7 @@ def metadata_id(self) -> Column:
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,
Expand Down Expand Up @@ -576,7 +573,7 @@ def entity_ids(self, point_in_time: datetime | None = None) -> list[str]:

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

Expand Down
7 changes: 3 additions & 4 deletions homeassistant/config_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
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
Expand Down Expand Up @@ -86,7 +88,6 @@

SAVE_DELAY = 1

_ConfigEntryStateSelfT = TypeVar("_ConfigEntryStateSelfT", bound="ConfigEntryState")
_R = TypeVar("_R")


Expand All @@ -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
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
)
from urllib.parse import urlparse

from typing_extensions import Self
import voluptuous as vol
import yarl

Expand Down Expand Up @@ -1075,9 +1076,6 @@ def _async_remove_listener(
)


_StateT = TypeVar("_StateT", bound="State")


class State:
"""Object to represent a state within the state machine.
Expand Down Expand Up @@ -1200,7 +1198,7 @@ def as_compressed_state(self) -> dict[str, Any]:
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.
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/helpers/restore_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
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
Expand All @@ -32,8 +34,6 @@
# 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."""
Expand Down Expand Up @@ -82,7 +82,7 @@ def as_dict(self) -> dict[str, Any]:
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
Expand Down
9 changes: 3 additions & 6 deletions tests/components/recorder/db_schema_30.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
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
Expand All @@ -33,6 +33,7 @@
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 (
Expand Down Expand Up @@ -62,8 +63,6 @@

SCHEMA_VERSION = 30

_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")

_LOGGER = logging.getLogger(__name__)

TABLE_EVENTS = "events"
Expand Down Expand Up @@ -497,9 +496,7 @@ def metadata_id(self) -> Column:
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,
Expand Down

0 comments on commit 342b406

Please sign in to comment.