From 964c764dae1c7731664fb20e6eaac36cb5ef7bd3 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:19:46 +0200 Subject: [PATCH] Improve typing [helpers.sun] (#70892) --- .strict-typing | 1 + homeassistant/helpers/sun.py | 16 ++++++++++------ mypy.ini | 3 +++ 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.strict-typing b/.strict-typing index 546e99a96b8..f63122d66bb 100644 --- a/.strict-typing +++ b/.strict-typing @@ -20,6 +20,7 @@ homeassistant.helpers.entity_values homeassistant.helpers.event homeassistant.helpers.reload homeassistant.helpers.script_variables +homeassistant.helpers.sun homeassistant.helpers.translation homeassistant.util.async_ homeassistant.util.color diff --git a/homeassistant/helpers/sun.py b/homeassistant/helpers/sun.py index 09a329cd275..25bef38ed0b 100644 --- a/homeassistant/helpers/sun.py +++ b/homeassistant/helpers/sun.py @@ -1,8 +1,9 @@ """Helpers for sun events.""" from __future__ import annotations +from collections.abc import Callable import datetime -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast from homeassistant.const import SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET from homeassistant.core import HomeAssistant, callback @@ -11,11 +12,14 @@ from homeassistant.util import dt as dt_util if TYPE_CHECKING: import astral + import astral.location DATA_LOCATION_CACHE = "astral_location_cache" ELEVATION_AGNOSTIC_EVENTS = ("noon", "midnight") +_AstralSunEventCallable = Callable[..., datetime.datetime] + @callback @bind_hass @@ -73,15 +77,15 @@ def get_location_astral_event_next( if utc_point_in_time is None: utc_point_in_time = dt_util.utcnow() - kwargs = {"local": False} + kwargs: dict[str, Any] = {"local": False} if event not in ELEVATION_AGNOSTIC_EVENTS: kwargs["observer_elevation"] = elevation mod = -1 while True: try: - next_dt: datetime.datetime = ( - getattr(location, event)( + next_dt = ( + cast(_AstralSunEventCallable, getattr(location, event))( dt_util.as_local(utc_point_in_time).date() + datetime.timedelta(days=mod), **kwargs, @@ -111,12 +115,12 @@ def get_astral_event_date( if isinstance(date, datetime.datetime): date = dt_util.as_local(date).date() - kwargs = {"local": False} + kwargs: dict[str, Any] = {"local": False} if event not in ELEVATION_AGNOSTIC_EVENTS: kwargs["observer_elevation"] = elevation try: - return getattr(location, event)(date, **kwargs) # type: ignore[no-any-return] + return cast(_AstralSunEventCallable, getattr(location, event))(date, **kwargs) except ValueError: # Event never occurs for specified date. return None diff --git a/mypy.ini b/mypy.ini index 519191a77cd..abd37cb3783 100644 --- a/mypy.ini +++ b/mypy.ini @@ -71,6 +71,9 @@ disallow_any_generics = true [mypy-homeassistant.helpers.script_variables] disallow_any_generics = true +[mypy-homeassistant.helpers.sun] +disallow_any_generics = true + [mypy-homeassistant.helpers.translation] disallow_any_generics = true