Improve singleton helper typing (#75461)

* Improve singleton helper typing

* Fix type errors
This commit is contained in:
Marc Mueller 2022-07-21 00:19:02 +02:00 committed by GitHub
parent 6da25c733e
commit ac858cc2b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 12 additions and 10 deletions

View File

@ -25,6 +25,7 @@ homeassistant.helpers.entity_values
homeassistant.helpers.event
homeassistant.helpers.reload
homeassistant.helpers.script_variables
homeassistant.helpers.singleton
homeassistant.helpers.sun
homeassistant.helpers.translation
homeassistant.util.async_

View File

@ -305,9 +305,7 @@ class RestoreEntity(Entity):
# Return None if this entity isn't added to hass yet
_LOGGER.warning("Cannot get last state. Entity not added to hass") # type: ignore[unreachable]
return None
data = cast(
RestoreStateData, await RestoreStateData.async_get_instance(self.hass)
)
data = await RestoreStateData.async_get_instance(self.hass)
if self.entity_id not in data.last_states:
return None
return data.last_states[self.entity_id]

View File

@ -4,23 +4,23 @@ from __future__ import annotations
import asyncio
from collections.abc import Callable
import functools
from typing import TypeVar, cast
from typing import Any, TypeVar, cast
from homeassistant.core import HomeAssistant
from homeassistant.loader import bind_hass
_T = TypeVar("_T")
FUNC = Callable[[HomeAssistant], _T]
_FuncType = Callable[[HomeAssistant], _T]
def singleton(data_key: str) -> Callable[[FUNC], FUNC]:
def singleton(data_key: str) -> Callable[[_FuncType[_T]], _FuncType[_T]]:
"""Decorate a function that should be called once per instance.
Result will be cached and simultaneous calls will be handled.
"""
def wrapper(func: FUNC) -> FUNC:
def wrapper(func: _FuncType[_T]) -> _FuncType[_T]:
"""Wrap a function with caching logic."""
if not asyncio.iscoroutinefunction(func):
@ -35,10 +35,10 @@ def singleton(data_key: str) -> Callable[[FUNC], FUNC]:
@bind_hass
@functools.wraps(func)
async def async_wrapped(hass: HomeAssistant) -> _T:
async def async_wrapped(hass: HomeAssistant) -> Any:
if data_key not in hass.data:
evt = hass.data[data_key] = asyncio.Event()
result = await func(hass)
result = await func(hass) # type: ignore[misc]
hass.data[data_key] = result
evt.set()
return cast(_T, result)
@ -51,6 +51,6 @@ def singleton(data_key: str) -> Callable[[FUNC], FUNC]:
return cast(_T, obj_or_evt)
return async_wrapped
return async_wrapped # type: ignore[return-value]
return wrapper

View File

@ -87,6 +87,9 @@ disallow_any_generics = true
[mypy-homeassistant.helpers.script_variables]
disallow_any_generics = true
[mypy-homeassistant.helpers.singleton]
disallow_any_generics = true
[mypy-homeassistant.helpers.sun]
disallow_any_generics = true