mirror of
https://github.com/home-assistant/core.git
synced 2025-07-19 03:07:37 +00:00
Add Self typing (1) [mypy 1.0] (#87598)
This commit is contained in:
parent
a5d376069a
commit
342b406dc0
@ -2,17 +2,15 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from enum import Enum
|
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):
|
class StrEnum(str, Enum):
|
||||||
"""Partial backport of Python 3.11's StrEnum for our basic use cases."""
|
"""Partial backport of Python 3.11's StrEnum for our basic use cases."""
|
||||||
|
|
||||||
def __new__(
|
def __new__(cls, value: str, *args: Any, **kwargs: Any) -> Self:
|
||||||
cls: type[_StrEnumSelfT], value: str, *args: Any, **kwargs: Any
|
|
||||||
) -> _StrEnumSelfT:
|
|
||||||
"""Create a new StrEnum instance."""
|
"""Create a new StrEnum instance."""
|
||||||
if not isinstance(value, str):
|
if not isinstance(value, str):
|
||||||
raise TypeError(f"{value!r} is not a string")
|
raise TypeError(f"{value!r} is not a string")
|
||||||
|
@ -3,10 +3,11 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from collections.abc import MutableMapping
|
from collections.abc import MutableMapping
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import TypeVar, cast
|
from typing import cast
|
||||||
|
|
||||||
from bleak.backends.service import BleakGATTServiceCollection
|
from bleak.backends.service import BleakGATTServiceCollection
|
||||||
from lru import LRU # pylint: disable=no-name-in-module
|
from lru import LRU # pylint: disable=no-name-in-module
|
||||||
|
from typing_extensions import Self
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
@ -19,8 +20,6 @@ from .entry_data import RuntimeEntryData
|
|||||||
STORAGE_VERSION = 1
|
STORAGE_VERSION = 1
|
||||||
MAX_CACHED_SERVICES = 128
|
MAX_CACHED_SERVICES = 128
|
||||||
|
|
||||||
_DomainDataSelfT = TypeVar("_DomainDataSelfT", bound="DomainData")
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class DomainData:
|
class DomainData:
|
||||||
@ -94,10 +93,10 @@ class DomainData:
|
|||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get(cls: type[_DomainDataSelfT], hass: HomeAssistant) -> _DomainDataSelfT:
|
def get(cls, hass: HomeAssistant) -> Self:
|
||||||
"""Get the global DomainData instance stored in hass.data."""
|
"""Get the global DomainData instance stored in hass.data."""
|
||||||
# Don't use setdefault - this is a hot code path
|
# Don't use setdefault - this is a hot code path
|
||||||
if DOMAIN in hass.data:
|
if DOMAIN in hass.data:
|
||||||
return cast(_DomainDataSelfT, hass.data[DOMAIN])
|
return cast(Self, hass.data[DOMAIN])
|
||||||
ret = hass.data[DOMAIN] = cls()
|
ret = hass.data[DOMAIN] = cls()
|
||||||
return ret
|
return ret
|
||||||
|
@ -5,7 +5,7 @@ from collections.abc import Callable
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
from typing import Any, TypeVar, cast
|
from typing import Any, cast
|
||||||
|
|
||||||
import ciso8601
|
import ciso8601
|
||||||
from fnvhash import fnv1a_32
|
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.ext.declarative import declared_attr
|
||||||
from sqlalchemy.orm import aliased, declarative_base, relationship
|
from sqlalchemy.orm import aliased, declarative_base, relationship
|
||||||
from sqlalchemy.orm.session import Session
|
from sqlalchemy.orm.session import Session
|
||||||
|
from typing_extensions import Self
|
||||||
|
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
MAX_LENGTH_EVENT_CONTEXT_ID,
|
MAX_LENGTH_EVENT_CONTEXT_ID,
|
||||||
@ -57,8 +58,6 @@ Base = declarative_base()
|
|||||||
|
|
||||||
SCHEMA_VERSION = 33
|
SCHEMA_VERSION = 33
|
||||||
|
|
||||||
_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
TABLE_EVENTS = "events"
|
TABLE_EVENTS = "events"
|
||||||
@ -472,9 +471,7 @@ class StatisticsBase:
|
|||||||
sum = Column(DOUBLE_TYPE)
|
sum = Column(DOUBLE_TYPE)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_stats(
|
def from_stats(cls, metadata_id: int, stats: StatisticData) -> Self:
|
||||||
cls: type[_StatisticsBaseSelfT], metadata_id: int, stats: StatisticData
|
|
||||||
) -> _StatisticsBaseSelfT:
|
|
||||||
"""Create object from a statistics."""
|
"""Create object from a statistics."""
|
||||||
return cls( # type: ignore[call-arg,misc]
|
return cls( # type: ignore[call-arg,misc]
|
||||||
metadata_id=metadata_id,
|
metadata_id=metadata_id,
|
||||||
@ -576,7 +573,7 @@ class RecorderRuns(Base): # type: ignore[misc,valid-type]
|
|||||||
|
|
||||||
return [row[0] for row in query]
|
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, native format is this model."""
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@ -14,6 +14,8 @@ from types import MappingProxyType, MethodType
|
|||||||
from typing import TYPE_CHECKING, Any, TypeVar, cast
|
from typing import TYPE_CHECKING, Any, TypeVar, cast
|
||||||
import weakref
|
import weakref
|
||||||
|
|
||||||
|
from typing_extensions import Self
|
||||||
|
|
||||||
from . import data_entry_flow, loader
|
from . import data_entry_flow, loader
|
||||||
from .backports.enum import StrEnum
|
from .backports.enum import StrEnum
|
||||||
from .components import persistent_notification
|
from .components import persistent_notification
|
||||||
@ -86,7 +88,6 @@ PATH_CONFIG = ".config_entries.json"
|
|||||||
|
|
||||||
SAVE_DELAY = 1
|
SAVE_DELAY = 1
|
||||||
|
|
||||||
_ConfigEntryStateSelfT = TypeVar("_ConfigEntryStateSelfT", bound="ConfigEntryState")
|
|
||||||
_R = TypeVar("_R")
|
_R = TypeVar("_R")
|
||||||
|
|
||||||
|
|
||||||
@ -110,9 +111,7 @@ class ConfigEntryState(Enum):
|
|||||||
|
|
||||||
_recoverable: bool
|
_recoverable: bool
|
||||||
|
|
||||||
def __new__(
|
def __new__(cls, value: str, recoverable: bool) -> Self:
|
||||||
cls: type[_ConfigEntryStateSelfT], value: str, recoverable: bool
|
|
||||||
) -> _ConfigEntryStateSelfT:
|
|
||||||
"""Create new ConfigEntryState."""
|
"""Create new ConfigEntryState."""
|
||||||
obj = object.__new__(cls)
|
obj = object.__new__(cls)
|
||||||
obj._value_ = value
|
obj._value_ = value
|
||||||
|
@ -37,6 +37,7 @@ from typing import (
|
|||||||
)
|
)
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from typing_extensions import Self
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
import yarl
|
import yarl
|
||||||
|
|
||||||
@ -1075,9 +1076,6 @@ class EventBus:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
_StateT = TypeVar("_StateT", bound="State")
|
|
||||||
|
|
||||||
|
|
||||||
class State:
|
class State:
|
||||||
"""Object to represent a state within the state machine.
|
"""Object to represent a state within the state machine.
|
||||||
|
|
||||||
@ -1200,7 +1198,7 @@ class State:
|
|||||||
return compressed_state
|
return compressed_state
|
||||||
|
|
||||||
@classmethod
|
@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.
|
"""Initialize a state from a dict.
|
||||||
|
|
||||||
Async friendly.
|
Async friendly.
|
||||||
|
@ -5,7 +5,9 @@ from abc import ABC, abstractmethod
|
|||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import logging
|
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.const import ATTR_RESTORED, EVENT_HOMEASSISTANT_STOP
|
||||||
from homeassistant.core import HomeAssistant, State, callback, valid_entity_id
|
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
|
# How long should a saved state be preserved if the entity no longer exists
|
||||||
STATE_EXPIRATION = timedelta(days=7)
|
STATE_EXPIRATION = timedelta(days=7)
|
||||||
|
|
||||||
_StoredStateSelfT = TypeVar("_StoredStateSelfT", bound="StoredState")
|
|
||||||
|
|
||||||
|
|
||||||
class ExtraStoredData(ABC):
|
class ExtraStoredData(ABC):
|
||||||
"""Object to hold extra stored data."""
|
"""Object to hold extra stored data."""
|
||||||
@ -82,7 +82,7 @@ class StoredState:
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
@classmethod
|
@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."""
|
"""Initialize a stored state from a dict."""
|
||||||
extra_data_dict = json_dict.get("extra_data")
|
extra_data_dict = json_dict.get("extra_data")
|
||||||
extra_data = RestoredExtraData(extra_data_dict) if extra_data_dict else None
|
extra_data = RestoredExtraData(extra_data_dict) if extra_data_dict else None
|
||||||
|
@ -8,7 +8,7 @@ from __future__ import annotations
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, TypedDict, TypeVar, cast, overload
|
from typing import Any, TypedDict, cast, overload
|
||||||
|
|
||||||
import ciso8601
|
import ciso8601
|
||||||
from fnvhash import fnv1a_32
|
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.ext.declarative import declared_attr
|
||||||
from sqlalchemy.orm import aliased, declarative_base, relationship
|
from sqlalchemy.orm import aliased, declarative_base, relationship
|
||||||
from sqlalchemy.orm.session import Session
|
from sqlalchemy.orm.session import Session
|
||||||
|
from typing_extensions import Self
|
||||||
|
|
||||||
from homeassistant.components.recorder.const import SupportedDialect
|
from homeassistant.components.recorder.const import SupportedDialect
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
@ -62,8 +63,6 @@ Base = declarative_base()
|
|||||||
|
|
||||||
SCHEMA_VERSION = 30
|
SCHEMA_VERSION = 30
|
||||||
|
|
||||||
_StatisticsBaseSelfT = TypeVar("_StatisticsBaseSelfT", bound="StatisticsBase")
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
TABLE_EVENTS = "events"
|
TABLE_EVENTS = "events"
|
||||||
@ -497,9 +496,7 @@ class StatisticsBase:
|
|||||||
sum = Column(DOUBLE_TYPE)
|
sum = Column(DOUBLE_TYPE)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_stats(
|
def from_stats(cls, metadata_id: int, stats: StatisticData) -> Self:
|
||||||
cls: type[_StatisticsBaseSelfT], metadata_id: int, stats: StatisticData
|
|
||||||
) -> _StatisticsBaseSelfT:
|
|
||||||
"""Create object from a statistics."""
|
"""Create object from a statistics."""
|
||||||
return cls( # type: ignore[call-arg,misc]
|
return cls( # type: ignore[call-arg,misc]
|
||||||
metadata_id=metadata_id,
|
metadata_id=metadata_id,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user