Skip to content

Commit

Permalink
Type hint additions (home-assistant#26831)
Browse files Browse the repository at this point in the history
* Type hint additions

* Remove optional from sidebar_icon comment

Co-Authored-By: Franck Nijhof <frenck@frenck.nl>

* Remove optional from sidebar_title comment

Co-Authored-By: Franck Nijhof <frenck@frenck.nl>

* Fix issues after rebase and mypy 0.730
  • Loading branch information
scop committed Sep 29, 2019
1 parent 4f55235 commit f259ff1
Show file tree
Hide file tree
Showing 27 changed files with 184 additions and 68 deletions.
18 changes: 13 additions & 5 deletions homeassistant/components/automation/state.py
@@ -1,16 +1,19 @@
"""Offer state listening automation rules."""
from datetime import timedelta
import logging
from typing import Dict

import voluptuous as vol

from homeassistant import exceptions
from homeassistant.core import callback
from homeassistant.core import HomeAssistant, CALLBACK_TYPE, callback
from homeassistant.const import MATCH_ALL, CONF_PLATFORM, CONF_FOR
from homeassistant.helpers import config_validation as cv, template
from homeassistant.helpers.event import async_track_state_change, async_track_same_state


# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
# mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs
# mypy: no-check-untyped-defs

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -38,8 +41,13 @@


async def async_attach_trigger(
hass, config, action, automation_info, *, platform_type="state"
):
hass: HomeAssistant,
config,
action,
automation_info,
*,
platform_type: str = "state",
) -> CALLBACK_TYPE:
"""Listen for state changes based on configuration."""
entity_id = config.get(CONF_ENTITY_ID)
from_state = config.get(CONF_FROM, MATCH_ALL)
Expand All @@ -48,7 +56,7 @@ async def async_attach_trigger(
template.attach(hass, time_delta)
match_all = from_state == MATCH_ALL and to_state == MATCH_ALL
unsub_track_same = {}
period = {}
period: Dict[str, timedelta] = {}

@callback
def state_automation_listener(entity, from_s, to_s):
Expand Down
6 changes: 5 additions & 1 deletion homeassistant/components/device_automation/__init__.py
@@ -1,6 +1,7 @@
"""Helpers for device automations."""
import asyncio
import logging
from typing import Any, List, MutableMapping

import voluptuous as vol

Expand All @@ -11,6 +12,9 @@

from .exceptions import InvalidDeviceAutomationConfig


# mypy: allow-untyped-calls, allow-untyped-defs

DOMAIN = "device_automation"

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -96,7 +100,7 @@ async def _async_get_device_automations(hass, automation_type, device_id):
)

domains = set()
automations = []
automations: List[MutableMapping[str, Any]] = []
device = device_registry.async_get(device_id)
for entry_id in device.config_entries:
config_entry = hass.config_entries.async_get_entry(entry_id)
Expand Down
9 changes: 6 additions & 3 deletions homeassistant/components/device_automation/toggle_entity.py
@@ -1,5 +1,5 @@
"""Device automation helpers for toggle entity."""
from typing import List
from typing import Any, Dict, List
import voluptuous as vol

from homeassistant.core import Context, HomeAssistant, CALLBACK_TYPE
Expand All @@ -19,6 +19,9 @@
from homeassistant.helpers.typing import ConfigType, TemplateVarsType
from . import TRIGGER_BASE_SCHEMA


# mypy: allow-untyped-calls, allow-untyped-defs

ENTITY_ACTIONS = [
{
# Turn entity off
Expand Down Expand Up @@ -88,7 +91,7 @@ async def async_call_action_from_config(
variables: TemplateVarsType,
context: Context,
domain: str,
):
) -> None:
"""Change state based on configuration."""
config = ACTION_SCHEMA(config)
action_type = config[CONF_TYPE]
Expand Down Expand Up @@ -156,7 +159,7 @@ async def _async_get_automations(
hass: HomeAssistant, device_id: str, automation_templates: List[dict], domain: str
) -> List[dict]:
"""List device automations."""
automations = []
automations: List[Dict[str, Any]] = []
entity_registry = await hass.helpers.entity_registry.async_get_registry()

entries = [
Expand Down
16 changes: 8 additions & 8 deletions homeassistant/components/frontend/__init__.py
Expand Up @@ -4,7 +4,7 @@
import mimetypes
import os
import pathlib
from typing import Optional, Set, Tuple
from typing import Any, Dict, Optional, Set, Tuple

from aiohttp import web, web_urldispatcher, hdrs
import voluptuous as vol
Expand Down Expand Up @@ -122,19 +122,19 @@ class Panel:
"""Abstract class for panels."""

# Name of the webcomponent
component_name = None
component_name: Optional[str] = None

# Icon to show in the sidebar (optional)
sidebar_icon = None
# Icon to show in the sidebar
sidebar_icon: Optional[str] = None

# Title to show in the sidebar (optional)
sidebar_title = None
# Title to show in the sidebar
sidebar_title: Optional[str] = None

# Url to show the panel in the frontend
frontend_url_path = None
frontend_url_path: Optional[str] = None

# Config to pass to the webcomponent
config = None
config: Optional[Dict[str, Any]] = None

# If the panel should only be visible to admins
require_admin = False
Expand Down
14 changes: 10 additions & 4 deletions homeassistant/components/group/__init__.py
@@ -1,6 +1,7 @@
"""Provide the functionality to group entities."""
import asyncio
import logging
from typing import Any, Iterable, List, Optional, cast

import voluptuous as vol

Expand Down Expand Up @@ -32,9 +33,12 @@
from homeassistant.helpers.event import async_track_state_change
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ENTITY_SERVICE_SCHEMA
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util.async_ import run_coroutine_threadsafe


# mypy: allow-untyped-calls, allow-untyped-defs

DOMAIN = "group"

ENTITY_ID_FORMAT = DOMAIN + ".{}"
Expand Down Expand Up @@ -143,12 +147,12 @@ def is_on(hass, entity_id):


@bind_hass
def expand_entity_ids(hass, entity_ids):
def expand_entity_ids(hass: HomeAssistantType, entity_ids: Iterable[Any]) -> List[str]:
"""Return entity_ids with group entity ids replaced by their members.
Async friendly.
"""
found_ids = []
found_ids: List[str] = []
for entity_id in entity_ids:
if not isinstance(entity_id, str):
continue
Expand Down Expand Up @@ -182,7 +186,9 @@ def expand_entity_ids(hass, entity_ids):


@bind_hass
def get_entity_ids(hass, entity_id, domain_filter=None):
def get_entity_ids(
hass: HomeAssistantType, entity_id: str, domain_filter: Optional[str] = None
) -> List[str]:
"""Get members of this group.
Async friendly.
Expand All @@ -194,7 +200,7 @@ def get_entity_ids(hass, entity_id, domain_filter=None):

entity_ids = group.attributes[ATTR_ENTITY_ID]
if not domain_filter:
return entity_ids
return cast(List[str], entity_ids)

domain_filter = domain_filter.lower() + "."

Expand Down
26 changes: 21 additions & 5 deletions homeassistant/components/group/cover.py
@@ -1,5 +1,6 @@
"""This platform allows several cover to be grouped into one cover."""
import logging
from typing import Dict, Optional, Set

import voluptuous as vol

Expand All @@ -11,7 +12,7 @@
CONF_NAME,
STATE_CLOSED,
)
from homeassistant.core import callback
from homeassistant.core import callback, State
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change

Expand Down Expand Up @@ -41,6 +42,9 @@
CoverDevice,
)


# mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs

_LOGGER = logging.getLogger(__name__)

KEY_OPEN_CLOSE = "open_close"
Expand Down Expand Up @@ -76,13 +80,25 @@ def __init__(self, name, entities):
self._assumed_state = True

self._entities = entities
self._covers = {KEY_OPEN_CLOSE: set(), KEY_STOP: set(), KEY_POSITION: set()}
self._tilts = {KEY_OPEN_CLOSE: set(), KEY_STOP: set(), KEY_POSITION: set()}
self._covers: Dict[str, Set[str]] = {
KEY_OPEN_CLOSE: set(),
KEY_STOP: set(),
KEY_POSITION: set(),
}
self._tilts: Dict[str, Set[str]] = {
KEY_OPEN_CLOSE: set(),
KEY_STOP: set(),
KEY_POSITION: set(),
}

@callback
def update_supported_features(
self, entity_id, old_state, new_state, update_state=True
):
self,
entity_id: str,
old_state: Optional[State],
new_state: Optional[State],
update_state: bool = True,
) -> None:
"""Update dictionaries with supported features."""
if not new_state:
for values in self._covers.values():
Expand Down
11 changes: 8 additions & 3 deletions homeassistant/components/group/light.py
Expand Up @@ -3,7 +3,7 @@
from collections import Counter
import itertools
import logging
from typing import Any, Callable, Iterator, List, Optional, Tuple
from typing import Any, Callable, Iterator, List, Optional, Tuple, cast

import voluptuous as vol

Expand Down Expand Up @@ -43,6 +43,9 @@
SUPPORT_WHITE_VALUE,
)


# mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "Light Group"
Expand All @@ -69,7 +72,9 @@ async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
) -> None:
"""Initialize light.group platform."""
async_add_entities([LightGroup(config.get(CONF_NAME), config[CONF_ENTITIES])])
async_add_entities(
[LightGroup(cast(str, config.get(CONF_NAME)), config[CONF_ENTITIES])]
)


class LightGroup(light.Light):
Expand Down Expand Up @@ -263,7 +268,7 @@ async def async_turn_off(self, **kwargs):
async def async_update(self):
"""Query all members and determine the light group state."""
all_states = [self.hass.states.get(x) for x in self._entity_ids]
states = list(filter(None, all_states))
states: List[State] = list(filter(None, all_states))
on_states = [state for state in states if state.state == STATE_ON]

self._is_on = len(on_states) > 0
Expand Down
3 changes: 3 additions & 0 deletions homeassistant/components/group/notify.py
Expand Up @@ -17,6 +17,9 @@
BaseNotificationService,
)


# mypy: allow-untyped-calls, allow-untyped-defs

_LOGGER = logging.getLogger(__name__)

CONF_SERVICES = "services"
Expand Down
5 changes: 3 additions & 2 deletions homeassistant/components/media_player/__init__.py
Expand Up @@ -7,6 +7,7 @@
import hashlib
import logging
from random import SystemRandom
from typing import Optional
from urllib.parse import urlparse

from aiohttp import web
Expand Down Expand Up @@ -347,7 +348,7 @@ async def async_unload_entry(hass, entry):
class MediaPlayerDevice(Entity):
"""ABC for media player devices."""

_access_token = None
_access_token: Optional[str] = None

# Implement these for your media player
@property
Expand All @@ -356,7 +357,7 @@ def state(self):
return None

@property
def access_token(self):
def access_token(self) -> str:
"""Access token for this media player."""
if self._access_token is None:
self._access_token = hashlib.sha256(
Expand Down
20 changes: 14 additions & 6 deletions homeassistant/components/persistent_notification/__init__.py
@@ -1,7 +1,7 @@
"""Support for displaying persistent notifications."""
from collections import OrderedDict
import logging
from typing import Awaitable
from typing import Any, Mapping, MutableMapping, Optional

import voluptuous as vol

Expand All @@ -14,6 +14,9 @@
from homeassistant.util import slugify
import homeassistant.util.dt as dt_util


# mypy: allow-untyped-calls, allow-untyped-defs

ATTR_CREATED_AT = "created_at"
ATTR_MESSAGE = "message"
ATTR_NOTIFICATION_ID = "notification_id"
Expand Down Expand Up @@ -70,7 +73,10 @@ def dismiss(hass, notification_id):
@callback
@bind_hass
def async_create(
hass: HomeAssistant, message: str, title: str = None, notification_id: str = None
hass: HomeAssistant,
message: str,
title: Optional[str] = None,
notification_id: Optional[str] = None,
) -> None:
"""Generate a notification."""
data = {
Expand All @@ -95,9 +101,9 @@ def async_dismiss(hass: HomeAssistant, notification_id: str) -> None:
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))


async def async_setup(hass: HomeAssistant, config: dict) -> Awaitable[bool]:
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Set up the persistent notification component."""
persistent_notifications = OrderedDict()
persistent_notifications: MutableMapping[str, MutableMapping] = OrderedDict()
hass.data[DOMAIN] = {"notifications": persistent_notifications}

@callback
Expand Down Expand Up @@ -201,8 +207,10 @@ def mark_read_service(call):

@callback
def websocket_get_notifications(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg
):
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: Mapping[str, Any],
) -> None:
"""Return a list of persistent_notifications."""
connection.send_message(
websocket_api.result_message(
Expand Down
3 changes: 3 additions & 0 deletions homeassistant/components/sun/__init__.py
Expand Up @@ -17,6 +17,9 @@
)
from homeassistant.util import dt as dt_util


# mypy: allow-untyped-calls, allow-untyped-defs

_LOGGER = logging.getLogger(__name__)

DOMAIN = "sun"
Expand Down

0 comments on commit f259ff1

Please sign in to comment.