Skip to content

Commit

Permalink
Improve typing [helpers.sun] (#70892)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p committed Apr 27, 2022
1 parent 7dfe859 commit 964c764
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
1 change: 1 addition & 0 deletions .strict-typing
Expand Up @@ -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
Expand Down
16 changes: 10 additions & 6 deletions 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
Expand All @@ -11,11 +12,14 @@

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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions mypy.ini
Expand Up @@ -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

Expand Down

0 comments on commit 964c764

Please sign in to comment.