From 33e1b44b3a5724e254a4d60691c881ef3d687a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sat, 7 Sep 2019 09:48:58 +0300 Subject: [PATCH] Use PEP 526 type annotations, add some type hints (#26464) * Add some more type hints to helpers.event * Change most type comments to variable types * Remove some superfluous type hints --- homeassistant/auth/models.py | 12 +++---- .../components/bbox/device_tracker.py | 4 +-- homeassistant/components/bbox/sensor.py | 2 +- homeassistant/components/buienradar/camera.py | 6 ++-- homeassistant/components/cast/media_player.py | 25 ++++++------- .../components/device_tracker/config_entry.py | 2 +- .../components/device_tracker/legacy.py | 18 +++++----- .../components/device_tracker/setup.py | 2 +- homeassistant/components/ebox/sensor.py | 8 ++--- homeassistant/components/esphome/__init__.py | 8 ++--- .../components/esphome/config_flow.py | 10 +++--- homeassistant/components/fan/__init__.py | 14 ++++---- homeassistant/components/fido/sensor.py | 8 ++--- homeassistant/components/fints/sensor.py | 14 ++++---- .../components/google_assistant/http.py | 2 +- .../components/google_assistant/smart_home.py | 4 +-- homeassistant/components/group/light.py | 26 +++++++------- homeassistant/components/gtfs/sensor.py | 8 ++--- .../components/hydroquebec/sensor.py | 6 ++-- homeassistant/components/isy994/__init__.py | 2 +- homeassistant/components/mqtt/__init__.py | 36 +++++++++---------- .../components/onkyo/media_player.py | 6 ++-- homeassistant/components/person/__init__.py | 8 ++--- .../components/proximity/__init__.py | 4 +-- homeassistant/components/recorder/__init__.py | 8 ++--- homeassistant/components/startca/sensor.py | 4 +-- homeassistant/components/switch/light.py | 8 ++--- .../components/switcher_kis/switch.py | 2 +- homeassistant/components/teksavvy/sensor.py | 4 +-- .../components/webostv/media_player.py | 4 +-- homeassistant/components/zha/core/store.py | 6 ++-- homeassistant/helpers/entity_registry.py | 4 +-- homeassistant/helpers/event.py | 17 +++++---- homeassistant/loader.py | 32 ++++------------- tests/components/switcher_kis/conftest.py | 2 +- 35 files changed, 152 insertions(+), 174 deletions(-) diff --git a/homeassistant/auth/models.py b/homeassistant/auth/models.py index 26055032422..6889d17a25f 100644 --- a/homeassistant/auth/models.py +++ b/homeassistant/auth/models.py @@ -20,7 +20,7 @@ TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token" class Group: """A group.""" - name = attr.ib(type=str) # type: Optional[str] + name = attr.ib(type=Optional[str]) policy = attr.ib(type=perm_mdl.PolicyType) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) system_generated = attr.ib(type=bool, default=False) @@ -30,22 +30,20 @@ class Group: class User: """A user.""" - name = attr.ib(type=str) # type: Optional[str] + name = attr.ib(type=Optional[str]) perm_lookup = attr.ib(type=perm_mdl.PermissionLookup, cmp=False) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_owner = attr.ib(type=bool, default=False) is_active = attr.ib(type=bool, default=False) system_generated = attr.ib(type=bool, default=False) - groups = attr.ib(type=List, factory=list, cmp=False) # type: List[Group] + groups = attr.ib(type=List[Group], factory=list, cmp=False) # List of credentials of a user. - credentials = attr.ib(type=list, factory=list, cmp=False) # type: List[Credentials] + credentials = attr.ib(type=List["Credentials"], factory=list, cmp=False) # Tokens associated with a user. - refresh_tokens = attr.ib( - type=dict, factory=dict, cmp=False - ) # type: Dict[str, RefreshToken] + refresh_tokens = attr.ib(type=Dict[str, "RefreshToken"], factory=dict, cmp=False) _permissions = attr.ib( type=Optional[perm_mdl.PolicyPermissions], init=False, cmp=False, default=None diff --git a/homeassistant/components/bbox/device_tracker.py b/homeassistant/components/bbox/device_tracker.py index b565d05685f..89449aeab45 100644 --- a/homeassistant/components/bbox/device_tracker.py +++ b/homeassistant/components/bbox/device_tracker.py @@ -2,6 +2,7 @@ from collections import namedtuple from datetime import timedelta import logging +from typing import List import voluptuous as vol @@ -41,12 +42,11 @@ class BboxDeviceScanner(DeviceScanner): def __init__(self, config): """Get host from config.""" - from typing import List # noqa: pylint: disable=unused-import self.host = config[CONF_HOST] """Initialize the scanner.""" - self.last_results = [] # type: List[Device] + self.last_results: List[Device] = [] self.success_init = self._update_info() _LOGGER.info("Scanner initialized") diff --git a/homeassistant/components/bbox/sensor.py b/homeassistant/components/bbox/sensor.py index b59b166e41f..ba38f8d2607 100644 --- a/homeassistant/components/bbox/sensor.py +++ b/homeassistant/components/bbox/sensor.py @@ -13,7 +13,7 @@ from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) -BANDWIDTH_MEGABITS_SECONDS = "Mb/s" # type: str +BANDWIDTH_MEGABITS_SECONDS = "Mb/s" ATTRIBUTION = "Powered by Bouygues Telecom" diff --git a/homeassistant/components/buienradar/camera.py b/homeassistant/components/buienradar/camera.py index 1db9e2beaf9..cdf202bbafd 100644 --- a/homeassistant/components/buienradar/camera.py +++ b/homeassistant/components/buienradar/camera.py @@ -81,13 +81,13 @@ class BuienradarCam(Camera): # invariant: this condition is private to and owned by this instance. self._condition = asyncio.Condition() - self._last_image = None # type: Optional[bytes] + self._last_image: Optional[bytes] = None # value of the last seen last modified header - self._last_modified = None # type: Optional[str] + self._last_modified: Optional[str] = None # loading status self._loading = False # deadline for image refresh - self.delta after last successful load - self._deadline = None # type: Optional[datetime] + self._deadline: Optional[datetime] = None @property def name(self) -> str: diff --git a/homeassistant/components/cast/media_player.py b/homeassistant/components/cast/media_player.py index af9f39f8ed4..26bcaccc247 100644 --- a/homeassistant/components/cast/media_player.py +++ b/homeassistant/components/cast/media_player.py @@ -525,32 +525,33 @@ class CastDevice(MediaPlayerDevice): "elected leader" itself. """ - def __init__(self, cast_info): + def __init__(self, cast_info: ChromecastInfo): """Initialize the cast device.""" - import pychromecast # noqa: pylint: disable=unused-import + import pychromecast - self._cast_info = cast_info # type: ChromecastInfo + self._cast_info = cast_info self.services = None if cast_info.service: self.services = set() self.services.add(cast_info.service) - self._chromecast = None # type: Optional[pychromecast.Chromecast] + self._chromecast: Optional[pychromecast.Chromecast] = None self.cast_status = None self.media_status = None self.media_status_received = None - self._dynamic_group_cast_info = None # type: ChromecastInfo - self._dynamic_group_cast = None # type: Optional[pychromecast.Chromecast] + self._dynamic_group_cast_info: ChromecastInfo = None + self._dynamic_group_cast: Optional[pychromecast.Chromecast] = None self.dynamic_group_media_status = None self.dynamic_group_media_status_received = None self.mz_media_status = {} self.mz_media_status_received = {} self.mz_mgr = None - self._available = False # type: bool - self._dynamic_group_available = False # type: bool - self._status_listener = None # type: Optional[CastStatusListener] - self._dynamic_group_status_listener = ( - None - ) # type: Optional[DynamicGroupCastStatusListener] + self._available = False + self._dynamic_group_available = False + self._status_listener: Optional[CastStatusListener] = None + self._dynamic_group_status_listener: Optional[ + DynamicGroupCastStatusListener + ] = None + self._add_remove_handler = None self._del_remove_handler = None diff --git a/homeassistant/components/device_tracker/config_entry.py b/homeassistant/components/device_tracker/config_entry.py index 460f1198409..9e53c2e0cea 100644 --- a/homeassistant/components/device_tracker/config_entry.py +++ b/homeassistant/components/device_tracker/config_entry.py @@ -18,7 +18,7 @@ from .const import ATTR_SOURCE_TYPE, DOMAIN, LOGGER async def async_setup_entry(hass, entry): """Set up an entry.""" - component = hass.data.get(DOMAIN) # type: Optional[EntityComponent] + component: Optional[EntityComponent] = hass.data.get(DOMAIN) if component is None: component = hass.data[DOMAIN] = EntityComponent(LOGGER, DOMAIN, hass) diff --git a/homeassistant/components/device_tracker/legacy.py b/homeassistant/components/device_tracker/legacy.py index 2bfd0c41a47..5c186cc12a1 100644 --- a/homeassistant/components/device_tracker/legacy.py +++ b/homeassistant/components/device_tracker/legacy.py @@ -327,15 +327,15 @@ class DeviceTracker: class Device(RestoreEntity): """Represent a tracked device.""" - host_name = None # type: str - location_name = None # type: str - gps = None # type: GPSType - gps_accuracy = 0 # type: int - last_seen = None # type: dt_util.dt.datetime - consider_home = None # type: dt_util.dt.timedelta - battery = None # type: int - attributes = None # type: dict - icon = None # type: str + host_name: str = None + location_name: str = None + gps: GPSType = None + gps_accuracy: int = 0 + last_seen: dt_util.dt.datetime = None + consider_home: dt_util.dt.timedelta = None + battery: int = None + attributes: dict = None + icon: str = None # Track if the last update of this device was HOME. last_update_home = False diff --git a/homeassistant/components/device_tracker/setup.py b/homeassistant/components/device_tracker/setup.py index e6edb5f63ac..6c9f05dead7 100644 --- a/homeassistant/components/device_tracker/setup.py +++ b/homeassistant/components/device_tracker/setup.py @@ -147,7 +147,7 @@ def async_setup_scanner_platform( scanner.hass = hass # Initial scan of each mac we also tell about host name for config - seen = set() # type: Any + seen: Any = set() async def async_device_tracker_scan(now: dt_util.dt.datetime): """Handle interval matches.""" diff --git a/homeassistant/components/ebox/sensor.py b/homeassistant/components/ebox/sensor.py index 66c58b82882..95c5513ecaf 100644 --- a/homeassistant/components/ebox/sensor.py +++ b/homeassistant/components/ebox/sensor.py @@ -26,10 +26,10 @@ from homeassistant.exceptions import PlatformNotReady _LOGGER = logging.getLogger(__name__) -GIGABITS = "Gb" # type: str -PRICE = "CAD" # type: str -DAYS = "days" # type: str -PERCENT = "%" # type: str +GIGABITS = "Gb" +PRICE = "CAD" +DAYS = "days" +PERCENT = "%" DEFAULT_NAME = "EBox" diff --git a/homeassistant/components/esphome/__init__.py b/homeassistant/components/esphome/__init__.py index 182d4003e30..bc06aba94ea 100644 --- a/homeassistant/components/esphome/__init__.py +++ b/homeassistant/components/esphome/__init__.py @@ -203,7 +203,7 @@ async def _setup_auto_reconnect_logic( # When removing/disconnecting manually return - data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData + data: RuntimeEntryData = hass.data[DOMAIN][entry.entry_id] for disconnect_cb in data.disconnect_callbacks: disconnect_cb() data.disconnect_callbacks = [] @@ -326,7 +326,7 @@ async def _cleanup_instance( hass: HomeAssistantType, entry: ConfigEntry ) -> RuntimeEntryData: """Cleanup the esphome client if it exists.""" - data = hass.data[DATA_KEY].pop(entry.entry_id) # type: RuntimeEntryData + data: RuntimeEntryData = hass.data[DATA_KEY].pop(entry.entry_id) if data.reconnect_task is not None: data.reconnect_task.cancel() for disconnect_cb in data.disconnect_callbacks: @@ -363,7 +363,7 @@ async def platform_async_setup_entry( This method is in charge of receiving, distributing and storing info and state updates. """ - entry_data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData + entry_data: RuntimeEntryData = hass.data[DOMAIN][entry.entry_id] entry_data.info[component_key] = {} entry_data.state[component_key] = {} @@ -468,7 +468,7 @@ class EsphomeEntity(Entity): self._entry_id = entry_id self._component_key = component_key self._key = key - self._remove_callbacks = [] # type: List[Callable[[], None]] + self._remove_callbacks: List[Callable[[], None]] = [] async def async_added_to_hass(self) -> None: """Register callbacks.""" diff --git a/homeassistant/components/esphome/config_flow.py b/homeassistant/components/esphome/config_flow.py index 35389d055d6..9680ed46acd 100644 --- a/homeassistant/components/esphome/config_flow.py +++ b/homeassistant/components/esphome/config_flow.py @@ -19,9 +19,9 @@ class EsphomeFlowHandler(config_entries.ConfigFlow): def __init__(self): """Initialize flow.""" - self._host = None # type: Optional[str] - self._port = None # type: Optional[int] - self._password = None # type: Optional[str] + self._host: Optional[str] = None + self._port: Optional[int] = None + self._password: Optional[str] = None async def async_step_user( self, user_input: Optional[ConfigType] = None, error: Optional[str] = None @@ -94,9 +94,7 @@ class EsphomeFlowHandler(config_entries.ConfigFlow): already_configured = True elif entry.entry_id in self.hass.data.get(DATA_KEY, {}): # Does a config entry with this name already exist? - data = self.hass.data[DATA_KEY][ - entry.entry_id - ] # type: RuntimeEntryData + data: RuntimeEntryData = self.hass.data[DATA_KEY][entry.entry_id] # Node names are unique in the network if data.device_info is not None: already_configured = data.device_info.name == node_name diff --git a/homeassistant/components/fan/__init__.py b/homeassistant/components/fan/__init__.py index 50d698f7336..82f4d37938c 100644 --- a/homeassistant/components/fan/__init__.py +++ b/homeassistant/components/fan/__init__.py @@ -55,23 +55,21 @@ PROP_TO_ATTR = { "speed_list": ATTR_SPEED_LIST, "oscillating": ATTR_OSCILLATING, "current_direction": ATTR_DIRECTION, -} # type: dict +} FAN_SET_SPEED_SCHEMA = ENTITY_SERVICE_SCHEMA.extend( {vol.Required(ATTR_SPEED): cv.string} -) # type: dict +) -FAN_TURN_ON_SCHEMA = ENTITY_SERVICE_SCHEMA.extend( - {vol.Optional(ATTR_SPEED): cv.string} -) # type: dict +FAN_TURN_ON_SCHEMA = ENTITY_SERVICE_SCHEMA.extend({vol.Optional(ATTR_SPEED): cv.string}) FAN_OSCILLATE_SCHEMA = ENTITY_SERVICE_SCHEMA.extend( {vol.Required(ATTR_OSCILLATING): cv.boolean} -) # type: dict +) FAN_SET_DIRECTION_SCHEMA = ENTITY_SERVICE_SCHEMA.extend( {vol.Optional(ATTR_DIRECTION): cv.string} -) # type: dict +) @bind_hass @@ -198,7 +196,7 @@ class FanEntity(ToggleEntity): @property def state_attributes(self) -> dict: """Return optional state attributes.""" - data = {} # type: dict + data = {} for prop, attr in PROP_TO_ATTR.items(): if not hasattr(self, prop): diff --git a/homeassistant/components/fido/sensor.py b/homeassistant/components/fido/sensor.py index e85b45db4d3..8814a2406c5 100644 --- a/homeassistant/components/fido/sensor.py +++ b/homeassistant/components/fido/sensor.py @@ -25,10 +25,10 @@ import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) -KILOBITS = "Kb" # type: str -PRICE = "CAD" # type: str -MESSAGES = "messages" # type: str -MINUTES = "minutes" # type: str +KILOBITS = "Kb" +PRICE = "CAD" +MESSAGES = "messages" +MINUTES = "minutes" DEFAULT_NAME = "Fido" diff --git a/homeassistant/components/fints/sensor.py b/homeassistant/components/fints/sensor.py index 008337f88eb..376ea2c0f9d 100644 --- a/homeassistant/components/fints/sensor.py +++ b/homeassistant/components/fints/sensor.py @@ -162,11 +162,11 @@ class FinTsAccount(Entity): def __init__(self, client: FinTsClient, account, name: str) -> None: """Initialize a FinTs balance account.""" - self._client = client # type: FinTsClient + self._client = client self._account = account - self._name = name # type: str - self._balance = None # type: float - self._currency = None # type: str + self._name = name + self._balance: float = None + self._currency: str = None @property def should_poll(self) -> bool: @@ -222,11 +222,11 @@ class FinTsHoldingsAccount(Entity): def __init__(self, client: FinTsClient, account, name: str) -> None: """Initialize a FinTs holdings account.""" - self._client = client # type: FinTsClient - self._name = name # type: str + self._client = client + self._name = name self._account = account self._holdings = [] - self._total = None # type: float + self._total: float = None @property def should_poll(self) -> bool: diff --git a/homeassistant/components/google_assistant/http.py b/homeassistant/components/google_assistant/http.py index 24502462512..d68650fb638 100644 --- a/homeassistant/components/google_assistant/http.py +++ b/homeassistant/components/google_assistant/http.py @@ -93,7 +93,7 @@ class GoogleAssistantView(HomeAssistantView): async def post(self, request: Request) -> Response: """Handle Google Assistant requests.""" - message = await request.json() # type: dict + message: dict = await request.json() result = await async_handle_message( request.app["hass"], self.config, request["hass_user"].id, message ) diff --git a/homeassistant/components/google_assistant/smart_home.py b/homeassistant/components/google_assistant/smart_home.py index 2cb440f9181..6ab6d937b51 100644 --- a/homeassistant/components/google_assistant/smart_home.py +++ b/homeassistant/components/google_assistant/smart_home.py @@ -24,7 +24,7 @@ _LOGGER = logging.getLogger(__name__) async def async_handle_message(hass, config, user_id, message): """Handle incoming API messages.""" - request_id = message.get("requestId") # type: str + request_id: str = message.get("requestId") data = RequestData(config, user_id, request_id) @@ -38,7 +38,7 @@ async def async_handle_message(hass, config, user_id, message): async def _process(hass, data, message): """Process a message.""" - inputs = message.get("inputs") # type: list + inputs: list = message.get("inputs") if len(inputs) != 1: return { diff --git a/homeassistant/components/group/light.py b/homeassistant/components/group/light.py index f0d29d923c8..87d8134ccbf 100644 --- a/homeassistant/components/group/light.py +++ b/homeassistant/components/group/light.py @@ -75,19 +75,19 @@ class LightGroup(light.Light): def __init__(self, name: str, entity_ids: List[str]) -> None: """Initialize a light group.""" - self._name = name # type: str - self._entity_ids = entity_ids # type: List[str] - self._is_on = False # type: bool - self._available = False # type: bool - self._brightness = None # type: Optional[int] - self._hs_color = None # type: Optional[Tuple[float, float]] - self._color_temp = None # type: Optional[int] - self._min_mireds = 154 # type: Optional[int] - self._max_mireds = 500 # type: Optional[int] - self._white_value = None # type: Optional[int] - self._effect_list = None # type: Optional[List[str]] - self._effect = None # type: Optional[str] - self._supported_features = 0 # type: int + self._name = name + self._entity_ids = entity_ids + self._is_on = False + self._available = False + self._brightness: Optional[int] = None + self._hs_color: Optional[Tuple[float, float]] = None + self._color_temp: Optional[int] = None + self._min_mireds: Optional[int] = 154 + self._max_mireds: Optional[int] = 500 + self._white_value: Optional[int] = None + self._effect_list: Optional[List[str]] = None + self._effect: Optional[str] = None + self._supported_features: int = 0 self._async_unsub_state_changed = None async def async_added_to_hass(self) -> None: diff --git a/homeassistant/components/gtfs/sensor.py b/homeassistant/components/gtfs/sensor.py index d70e1016f07..eb662d8b2c9 100644 --- a/homeassistant/components/gtfs/sensor.py +++ b/homeassistant/components/gtfs/sensor.py @@ -256,7 +256,7 @@ def get_next_departure( _LOGGER.debug("Timetable: %s", sorted(timetable.keys())) - item = {} # type: dict + item = {} for key in sorted(timetable.keys()): if dt_util.parse_datetime(key) > now: item = timetable[key] @@ -393,11 +393,11 @@ class GTFSDepartureSensor(Entity): self._available = False self._icon = ICON self._name = "" - self._state = None # type: Optional[str] - self._attributes = {} # type: dict + self._state: Optional[str] = None + self._attributes = {} self._agency = None - self._departure = {} # type: dict + self._departure = {} self._destination = None self._origin = None self._route = None diff --git a/homeassistant/components/hydroquebec/sensor.py b/homeassistant/components/hydroquebec/sensor.py index fd713e8b7a7..c3ad79c1c98 100644 --- a/homeassistant/components/hydroquebec/sensor.py +++ b/homeassistant/components/hydroquebec/sensor.py @@ -28,9 +28,9 @@ import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) KILOWATT_HOUR = ENERGY_KILO_WATT_HOUR -PRICE = "CAD" # type: str -DAYS = "days" # type: str -CONF_CONTRACT = "contract" # type: str +PRICE = "CAD" +DAYS = "days" +CONF_CONTRACT = "contract" DEFAULT_NAME = "HydroQuebec" diff --git a/homeassistant/components/isy994/__init__.py b/homeassistant/components/isy994/__init__.py index e1d24fa5551..727ec91dc37 100644 --- a/homeassistant/components/isy994/__init__.py +++ b/homeassistant/components/isy994/__init__.py @@ -459,7 +459,7 @@ class ISYDevice(Entity): """Representation of an ISY994 device.""" _attrs = {} - _name = None # type: str + _name: str = None def __init__(self, node) -> None: """Initialize the insteon device.""" diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 75552d1d14b..8d83cd0cc2b 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -10,7 +10,7 @@ import os import socket import ssl import time -from typing import Any, Callable, List, Optional, Union, cast # noqa: F401 +from typing import Any, Callable, List, Optional, Union import attr import requests.certs @@ -479,7 +479,7 @@ async def _async_setup_server(hass: HomeAssistantType, config: ConfigType): This method is a coroutine. """ - conf = config.get(DOMAIN, {}) # type: ConfigType + conf: ConfigType = config.get(DOMAIN, {}) success, broker_config = await server.async_start( hass, conf.get(CONF_PASSWORD), conf.get(CONF_EMBEDDED) @@ -502,16 +502,16 @@ async def _async_setup_discovery( _LOGGER.error("Unable to load MQTT discovery") return False - success = await discovery.async_start( + success: bool = await discovery.async_start( hass, conf[CONF_DISCOVERY_PREFIX], hass_config, config_entry - ) # type: bool + ) return success async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Start the MQTT protocol service.""" - conf = config.get(DOMAIN) # type: Optional[ConfigType] + conf: Optional[ConfigType] = config.get(DOMAIN) # We need this because discovery can cause components to be set up and # otherwise it will not load the users config. @@ -621,7 +621,7 @@ async def async_setup_entry(hass, entry): birth_message = None # Be able to override versions other than TLSv1.0 under Python3.6 - conf_tls_version = conf.get(CONF_TLS_VERSION) # type: str + conf_tls_version: str = conf.get(CONF_TLS_VERSION) if conf_tls_version == "1.2": tls_version = ssl.PROTOCOL_TLSv1_2 elif conf_tls_version == "1.1": @@ -655,7 +655,7 @@ async def async_setup_entry(hass, entry): tls_version=tls_version, ) - result = await hass.data[DATA_MQTT].async_connect() # type: str + result: str = await hass.data[DATA_MQTT].async_connect() if result == CONNECTION_FAILED: return False @@ -671,11 +671,11 @@ async def async_setup_entry(hass, entry): async def async_publish_service(call: ServiceCall): """Handle MQTT publish service calls.""" - msg_topic = call.data[ATTR_TOPIC] # type: str + msg_topic: str = call.data[ATTR_TOPIC] payload = call.data.get(ATTR_PAYLOAD) payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE) - qos = call.data[ATTR_QOS] # type: int - retain = call.data[ATTR_RETAIN] # type: bool + qos: int = call.data[ATTR_QOS] + retain: bool = call.data[ATTR_RETAIN] if payload_template is not None: try: payload = template.Template(payload_template, hass).async_render() @@ -741,14 +741,14 @@ class MQTT: self.broker = broker self.port = port self.keepalive = keepalive - self.subscriptions = [] # type: List[Subscription] + self.subscriptions: List[Subscription] = [] self.birth_message = birth_message self.connected = False - self._mqttc = None # type: mqtt.Client + self._mqttc: mqtt.Client = None self._paho_lock = asyncio.Lock() if protocol == PROTOCOL_31: - proto = mqtt.MQTTv31 # type: int + proto: int = mqtt.MQTTv31 else: proto = mqtt.MQTTv311 @@ -796,7 +796,7 @@ class MQTT: This method is a coroutine. """ - result = None # type: int + result: int = None try: result = await self.hass.async_add_job( self._mqttc.connect, self.broker, self.port, self.keepalive @@ -870,7 +870,7 @@ class MQTT: This method is a coroutine. """ async with self._paho_lock: - result = None # type: int + result: int = None result, _ = await self.hass.async_add_job(self._mqttc.unsubscribe, topic) _raise_on_error(result) @@ -879,7 +879,7 @@ class MQTT: _LOGGER.debug("Subscribing to %s", topic) async with self._paho_lock: - result = None # type: int + result: int = None result, _ = await self.hass.async_add_job(self._mqttc.subscribe, topic, qos) _raise_on_error(result) @@ -928,7 +928,7 @@ class MQTT: if not _match_topic(subscription.topic, msg.topic): continue - payload = msg.payload # type: SubscribePayloadType + payload: SubscribePayloadType = msg.payload if subscription.encoding is not None: try: payload = msg.payload.decode(subscription.encoding) @@ -1077,7 +1077,7 @@ class MqttAvailability(Entity): def __init__(self, config: dict) -> None: """Initialize the availability mixin.""" self._availability_sub_state = None - self._available = False # type: bool + self._available = False self._avail_config = config diff --git a/homeassistant/components/onkyo/media_player.py b/homeassistant/components/onkyo/media_player.py index b5001a1f983..023fb32e6e4 100644 --- a/homeassistant/components/onkyo/media_player.py +++ b/homeassistant/components/onkyo/media_player.py @@ -1,8 +1,6 @@ """Support for Onkyo Receivers.""" import logging - -# pylint: disable=unused-import -from typing import List # noqa: F401 +from typing import List import voluptuous as vol @@ -54,7 +52,7 @@ SUPPORT_ONKYO_WO_VOLUME = ( | SUPPORT_PLAY_MEDIA ) -KNOWN_HOSTS = [] # type: List[str] +KNOWN_HOSTS: List[str] = [] DEFAULT_SOURCES = { "tv": "TV", "bd": "Bluray", diff --git a/homeassistant/components/person/__init__.py b/homeassistant/components/person/__init__.py index c6a2f91bab3..832853c670d 100644 --- a/homeassistant/components/person/__init__.py +++ b/homeassistant/components/person/__init__.py @@ -441,7 +441,7 @@ def ws_list_person( hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg ): """List persons.""" - manager = hass.data[DOMAIN] # type: PersonManager + manager: PersonManager = hass.data[DOMAIN] connection.send_result( msg["id"], {"storage": manager.storage_persons, "config": manager.config_persons}, @@ -464,7 +464,7 @@ async def ws_create_person( hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg ): """Create a person.""" - manager = hass.data[DOMAIN] # type: PersonManager + manager: PersonManager = hass.data[DOMAIN] try: person = await manager.async_create_person( name=msg["name"], @@ -495,7 +495,7 @@ async def ws_update_person( hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg ): """Update a person.""" - manager = hass.data[DOMAIN] # type: PersonManager + manager: PersonManager = hass.data[DOMAIN] changes = {} for key in ("name", "user_id", "device_trackers"): if key in msg: @@ -519,7 +519,7 @@ async def ws_delete_person( hass: HomeAssistantType, connection: websocket_api.ActiveConnection, msg ): """Delete a person.""" - manager = hass.data[DOMAIN] # type: PersonManager + manager: PersonManager = hass.data[DOMAIN] await manager.async_delete_person(msg["person_id"]) connection.send_result(msg["id"]) diff --git a/homeassistant/components/proximity/__init__.py b/homeassistant/components/proximity/__init__.py index b5856b7f78e..1f86958d08e 100644 --- a/homeassistant/components/proximity/__init__.py +++ b/homeassistant/components/proximity/__init__.py @@ -211,8 +211,8 @@ class Proximity(Entity): # Loop through each of the distances collected and work out the # closest. - closest_device = None # type: str - dist_to_zone = None # type: float + closest_device: str = None + dist_to_zone: float = None for device in distances_to_zone: if not dist_to_zone or distances_to_zone[device] < dist_to_zone: diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index 0d814a5d74b..9d34cc6fb79 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -7,7 +7,7 @@ import logging import queue import threading import time -from typing import Any, Dict, Optional # noqa: F401 +from typing import Any, Dict, Optional import voluptuous as vol @@ -177,12 +177,12 @@ class Recorder(threading.Thread): self.hass = hass self.keep_days = keep_days self.purge_interval = purge_interval - self.queue = queue.Queue() # type: Any + self.queue: Any = queue.Queue() self.recording_start = dt_util.utcnow() self.db_url = uri self.async_db_ready = asyncio.Future() - self.engine = None # type: Any - self.run_info = None # type: Any + self.engine: Any = None + self.run_info: Any = None self.entity_filter = generate_filter( include.get(CONF_DOMAINS, []), diff --git a/homeassistant/components/startca/sensor.py b/homeassistant/components/startca/sensor.py index 5e370ed7b63..1b567c58b45 100644 --- a/homeassistant/components/startca/sensor.py +++ b/homeassistant/components/startca/sensor.py @@ -18,8 +18,8 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Start.ca" CONF_TOTAL_BANDWIDTH = "total_bandwidth" -GIGABYTES = "GB" # type: str -PERCENT = "%" # type: str +GIGABYTES = "GB" +PERCENT = "%" MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1) REQUEST_TIMEOUT = 5 # seconds diff --git a/homeassistant/components/switch/light.py b/homeassistant/components/switch/light.py index 0b1094c0dd9..2027a8fc458 100644 --- a/homeassistant/components/switch/light.py +++ b/homeassistant/components/switch/light.py @@ -48,10 +48,10 @@ class LightSwitch(Light): def __init__(self, name: str, switch_entity_id: str) -> None: """Initialize Light Switch.""" - self._name = name # type: str - self._switch_entity_id = switch_entity_id # type: str - self._is_on = False # type: bool - self._available = False # type: bool + self._name = name + self._switch_entity_id = switch_entity_id + self._is_on = False + self._available = False self._async_unsub_state_changed = None @property diff --git a/homeassistant/components/switcher_kis/switch.py b/homeassistant/components/switcher_kis/switch.py index a758a584347..454baca4eef 100644 --- a/homeassistant/components/switcher_kis/switch.py +++ b/homeassistant/components/switcher_kis/switch.py @@ -143,7 +143,7 @@ class SwitcherControl(SwitchDevice): STATE_ON as SWITCHER_STATE_ON, ) - response = None # type: SwitcherV2ControlResponseMSG + response: "SwitcherV2ControlResponseMSG" = None async with SwitcherV2Api( self.hass.loop, self._device_data.ip_addr, diff --git a/homeassistant/components/teksavvy/sensor.py b/homeassistant/components/teksavvy/sensor.py index 74c39a221ba..dc8b16b8ce1 100644 --- a/homeassistant/components/teksavvy/sensor.py +++ b/homeassistant/components/teksavvy/sensor.py @@ -17,8 +17,8 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "TekSavvy" CONF_TOTAL_BANDWIDTH = "total_bandwidth" -GIGABYTES = "GB" # type: str -PERCENT = "%" # type: str +GIGABYTES = "GB" +PERCENT = "%" MIN_TIME_BETWEEN_UPDATES = timedelta(hours=1) REQUEST_TIMEOUT = 5 # seconds diff --git a/homeassistant/components/webostv/media_player.py b/homeassistant/components/webostv/media_player.py index 0b5696709fd..1da70bc60ec 100644 --- a/homeassistant/components/webostv/media_player.py +++ b/homeassistant/components/webostv/media_player.py @@ -3,7 +3,7 @@ import asyncio from datetime import timedelta import logging from urllib.parse import urlparse -from typing import Dict # noqa: F401 pylint: disable=unused-import +from typing import Dict import voluptuous as vol @@ -36,7 +36,7 @@ from homeassistant.const import ( import homeassistant.helpers.config_validation as cv from homeassistant.helpers.script import Script -_CONFIGURING = {} # type: Dict[str, str] +_CONFIGURING: Dict[str, str] = {} _LOGGER = logging.getLogger(__name__) CONF_SOURCES = "sources" diff --git a/homeassistant/components/zha/core/store.py b/homeassistant/components/zha/core/store.py index 85b4261e4ec..cea38517767 100644 --- a/homeassistant/components/zha/core/store.py +++ b/homeassistant/components/zha/core/store.py @@ -2,7 +2,7 @@ # pylint: disable=W0611 from collections import OrderedDict import logging -from typing import MutableMapping # noqa: F401 +from typing import MutableMapping from typing import cast import attr @@ -35,7 +35,7 @@ class ZhaDeviceStorage: def __init__(self, hass: HomeAssistantType) -> None: """Initialize the zha device storage.""" self.hass = hass - self.devices = {} # type: MutableMapping[str, ZhaDeviceEntry] + self.devices: MutableMapping[str, ZhaDeviceEntry] = {} self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) @callback @@ -88,7 +88,7 @@ class ZhaDeviceStorage: """Load the registry of zha device entries.""" data = await self._store.async_load() - devices = OrderedDict() # type: OrderedDict[str, ZhaDeviceEntry] + devices: "OrderedDict[str, ZhaDeviceEntry]" = OrderedDict() if data is not None: for device in data["devices"]: diff --git a/homeassistant/helpers/entity_registry.py b/homeassistant/helpers/entity_registry.py index 4b97aff19a8..00671e9c776 100644 --- a/homeassistant/helpers/entity_registry.py +++ b/homeassistant/helpers/entity_registry.py @@ -53,7 +53,7 @@ class RegistryEntry: device_id = attr.ib(type=str, default=None) config_entry_id = attr.ib(type=str, default=None) disabled_by = attr.ib( - type=str, + type=Optional[str], default=None, validator=attr.validators.in_( ( @@ -64,7 +64,7 @@ class RegistryEntry: None, ) ), - ) # type: Optional[str] + ) domain = attr.ib(type=str, init=False, repr=False) @domain.default diff --git a/homeassistant/helpers/event.py b/homeassistant/helpers/event.py index 3afb5cb88e4..b7707b844d4 100644 --- a/homeassistant/helpers/event.py +++ b/homeassistant/helpers/event.py @@ -1,5 +1,5 @@ """Helpers for listening to events.""" -from datetime import timedelta +from datetime import datetime, timedelta import functools as ft from typing import Callable @@ -21,8 +21,7 @@ from homeassistant.util import dt as dt_util from homeassistant.util.async_ import run_callback_threadsafe -# mypy: allow-incomplete-defs, allow-untyped-calls, allow-untyped-defs -# mypy: no-check-untyped-defs, no-warn-return-any +# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs # PyLint does not like the use of threaded_listener_factory # pylint: disable=invalid-name @@ -187,7 +186,9 @@ track_same_state = threaded_listener_factory(async_track_same_state) @callback @bind_hass -def async_track_point_in_time(hass, action, point_in_time) -> CALLBACK_TYPE: +def async_track_point_in_time( + hass: HomeAssistant, action: Callable[..., None], point_in_time: datetime +) -> CALLBACK_TYPE: """Add a listener that fires once after a specific point in time.""" utc_point_in_time = dt_util.as_utc(point_in_time) @@ -204,7 +205,9 @@ track_point_in_time = threaded_listener_factory(async_track_point_in_time) @callback @bind_hass -def async_track_point_in_utc_time(hass, action, point_in_time) -> CALLBACK_TYPE: +def async_track_point_in_utc_time( + hass: HomeAssistant, action: Callable[..., None], point_in_time: datetime +) -> CALLBACK_TYPE: """Add a listener that fires once after a specific point in UTC time.""" # Ensure point_in_time is UTC point_in_time = dt_util.as_utc(point_in_time) @@ -284,8 +287,8 @@ class SunListener: action = attr.ib(type=Callable) event = attr.ib(type=str) offset = attr.ib(type=timedelta) - _unsub_sun = attr.ib(default=None) - _unsub_config = attr.ib(default=None) + _unsub_sun: CALLBACK_TYPE = attr.ib(default=None) + _unsub_config: CALLBACK_TYPE = attr.ib(default=None) @callback def async_attach(self): diff --git a/homeassistant/loader.py b/homeassistant/loader.py index 70284348157..1a9a3d256ac 100644 --- a/homeassistant/loader.py +++ b/homeassistant/loader.py @@ -322,9 +322,7 @@ class CircularDependency(LoaderError): def _load_file( - hass, # type: HomeAssistant - comp_or_platform: str, - base_paths: List[str], + hass: "HomeAssistant", comp_or_platform: str, base_paths: List[str] ) -> Optional[ModuleType]: """Try to load specified file. @@ -391,11 +389,7 @@ def _load_file( class ModuleWrapper: """Class to wrap a Python module and auto fill in hass argument.""" - def __init__( - self, - hass, # type: HomeAssistant - module: ModuleType, - ) -> None: + def __init__(self, hass: "HomeAssistant", module: ModuleType) -> None: """Initialize the module wrapper.""" self._hass = hass self._module = module @@ -414,9 +408,7 @@ class ModuleWrapper: class Components: """Helper to load components.""" - def __init__( - self, hass # type: HomeAssistant - ) -> None: + def __init__(self, hass: "HomeAssistant") -> None: """Initialize the Components class.""" self._hass = hass @@ -442,9 +434,7 @@ class Components: class Helpers: """Helper to load helpers.""" - def __init__( - self, hass # type: HomeAssistant - ) -> None: + def __init__(self, hass: "HomeAssistant") -> None: """Initialize the Helpers class.""" self._hass = hass @@ -462,10 +452,7 @@ def bind_hass(func: CALLABLE_T) -> CALLABLE_T: return func -async def async_component_dependencies( - hass, # type: HomeAssistant - domain: str, -) -> Set[str]: +async def async_component_dependencies(hass: "HomeAssistant", domain: str) -> Set[str]: """Return all dependencies and subdependencies of components. Raises CircularDependency if a circular dependency is found. @@ -474,10 +461,7 @@ async def async_component_dependencies( async def _async_component_dependencies( - hass, # type: HomeAssistant - domain: str, - loaded: Set[str], - loading: Set, + hass: "HomeAssistant", domain: str, loaded: Set[str], loading: Set ) -> Set[str]: """Recursive function to get component dependencies. @@ -508,9 +492,7 @@ async def _async_component_dependencies( return loaded -def _async_mount_config_dir( - hass, # type: HomeAssistant -) -> bool: +def _async_mount_config_dir(hass: "HomeAssistant") -> bool: """Mount config dir in order to load custom_component. Async friendly but not a coroutine. diff --git a/tests/components/switcher_kis/conftest.py b/tests/components/switcher_kis/conftest.py index e0674691533..888ffd46c3b 100644 --- a/tests/components/switcher_kis/conftest.py +++ b/tests/components/switcher_kis/conftest.py @@ -93,7 +93,7 @@ class MockSwitcherV2Device: @fixture(name="mock_bridge") def mock_bridge_fixture() -> Generator[None, Any, None]: """Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.""" - queue = Queue() # type: Queue + queue = Queue() async def mock_queue(): """Mock asyncio's Queue."""