Various type hint improvements (#46144)

This commit is contained in:
Ville Skyttä 2021-02-08 12:59:46 +02:00 committed by GitHub
parent 54dce1c505
commit 82607977ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 34 additions and 16 deletions

View File

@ -51,6 +51,7 @@ from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_per_platform, extract_domain_configs from homeassistant.helpers import config_per_platform, extract_domain_configs
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_values import EntityValues from homeassistant.helpers.entity_values import EntityValues
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import Integration, IntegrationNotFound from homeassistant.loader import Integration, IntegrationNotFound
from homeassistant.requirements import ( from homeassistant.requirements import (
RequirementsNotFound, RequirementsNotFound,
@ -734,8 +735,8 @@ async def merge_packages_config(
async def async_process_component_config( async def async_process_component_config(
hass: HomeAssistant, config: Dict, integration: Integration hass: HomeAssistant, config: ConfigType, integration: Integration
) -> Optional[Dict]: ) -> Optional[ConfigType]:
"""Check component configuration and return processed configuration. """Check component configuration and return processed configuration.
Returns None on error. Returns None on error.

View File

@ -11,6 +11,8 @@ from homeassistant.util import slugify
from .typing import HomeAssistantType from .typing import HomeAssistantType
# mypy: disallow-any-generics
DATA_REGISTRY = "area_registry" DATA_REGISTRY = "area_registry"
EVENT_AREA_REGISTRY_UPDATED = "area_registry_updated" EVENT_AREA_REGISTRY_UPDATED = "area_registry_updated"
STORAGE_KEY = "core.area_registry" STORAGE_KEY = "core.area_registry"
@ -25,7 +27,7 @@ class AreaEntry:
name: str = attr.ib() name: str = attr.ib()
id: Optional[str] = attr.ib(default=None) id: Optional[str] = attr.ib(default=None)
def generate_id(self, existing_ids: Container) -> None: def generate_id(self, existing_ids: Container[str]) -> None:
"""Initialize ID.""" """Initialize ID."""
suggestion = suggestion_base = slugify(self.name) suggestion = suggestion_base = slugify(self.name)
tries = 1 tries = 1

View File

@ -9,6 +9,7 @@ from typing import Any, Callable, Collection, Dict, Optional, Union
from homeassistant import core, setup from homeassistant import core, setup
from homeassistant.const import ATTR_DISCOVERED, ATTR_SERVICE, EVENT_PLATFORM_DISCOVERED from homeassistant.const import ATTR_DISCOVERED, ATTR_SERVICE, EVENT_PLATFORM_DISCOVERED
from homeassistant.core import CALLBACK_TYPE
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.loader import bind_hass from homeassistant.loader import bind_hass
from homeassistant.util.async_ import run_callback_threadsafe from homeassistant.util.async_ import run_callback_threadsafe
@ -16,10 +17,14 @@ from homeassistant.util.async_ import run_callback_threadsafe
EVENT_LOAD_PLATFORM = "load_platform.{}" EVENT_LOAD_PLATFORM = "load_platform.{}"
ATTR_PLATFORM = "platform" ATTR_PLATFORM = "platform"
# mypy: disallow-any-generics
@bind_hass @bind_hass
def listen( def listen(
hass: core.HomeAssistant, service: Union[str, Collection[str]], callback: Callable hass: core.HomeAssistant,
service: Union[str, Collection[str]],
callback: CALLBACK_TYPE,
) -> None: ) -> None:
"""Set up listener for discovery of specific service. """Set up listener for discovery of specific service.
@ -31,7 +36,9 @@ def listen(
@core.callback @core.callback
@bind_hass @bind_hass
def async_listen( def async_listen(
hass: core.HomeAssistant, service: Union[str, Collection[str]], callback: Callable hass: core.HomeAssistant,
service: Union[str, Collection[str]],
callback: CALLBACK_TYPE,
) -> None: ) -> None:
"""Set up listener for discovery of specific service. """Set up listener for discovery of specific service.
@ -94,7 +101,7 @@ async def async_discover(
@bind_hass @bind_hass
def listen_platform( def listen_platform(
hass: core.HomeAssistant, component: str, callback: Callable hass: core.HomeAssistant, component: str, callback: CALLBACK_TYPE
) -> None: ) -> None:
"""Register a platform loader listener.""" """Register a platform loader listener."""
run_callback_threadsafe( run_callback_threadsafe(

View File

@ -272,7 +272,9 @@ class EntityComponent:
if found: if found:
await found.async_remove_entity(entity_id) await found.async_remove_entity(entity_id)
async def async_prepare_reload(self, *, skip_reset: bool = False) -> Optional[dict]: async def async_prepare_reload(
self, *, skip_reset: bool = False
) -> Optional[ConfigType]:
"""Prepare reloading this entity component. """Prepare reloading this entity component.
This method must be run in the event loop. This method must be run in the event loop.

View File

@ -2,7 +2,7 @@
import asyncio import asyncio
import logging import logging
from typing import Any, Dict, Iterable, List, Optional from typing import Dict, Iterable, List, Optional
from homeassistant import config as conf_util from homeassistant import config as conf_util
from homeassistant.const import SERVICE_RELOAD from homeassistant.const import SERVICE_RELOAD
@ -10,7 +10,7 @@ from homeassistant.core import Event, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_per_platform from homeassistant.helpers import config_per_platform
from homeassistant.helpers.entity_platform import EntityPlatform, async_get_platforms from homeassistant.helpers.entity_platform import EntityPlatform, async_get_platforms
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from homeassistant.loader import async_get_integration from homeassistant.loader import async_get_integration
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -49,7 +49,7 @@ async def _resetup_platform(
hass: HomeAssistantType, hass: HomeAssistantType,
integration_name: str, integration_name: str,
integration_platform: str, integration_platform: str,
unprocessed_conf: Dict, unprocessed_conf: ConfigType,
) -> None: ) -> None:
"""Resetup a platform.""" """Resetup a platform."""
integration = await async_get_integration(hass, integration_platform) integration = await async_get_integration(hass, integration_platform)
@ -129,7 +129,7 @@ async def _async_reconfig_platform(
async def async_integration_yaml_config( async def async_integration_yaml_config(
hass: HomeAssistantType, integration_name: str hass: HomeAssistantType, integration_name: str
) -> Optional[Dict[Any, Any]]: ) -> Optional[ConfigType]:
"""Fetch the latest yaml configuration for an integration.""" """Fetch the latest yaml configuration for an integration."""
integration = await async_get_integration(hass, integration_name) integration = await async_get_integration(hass, integration_name)

View File

@ -779,7 +779,7 @@ async def _async_stop_scripts_at_shutdown(hass, event):
_VarsType = Union[Dict[str, Any], MappingProxyType] _VarsType = Union[Dict[str, Any], MappingProxyType]
def _referenced_extract_ids(data: Dict, key: str, found: Set[str]) -> None: def _referenced_extract_ids(data: Dict[str, Any], key: str, found: Set[str]) -> None:
"""Extract referenced IDs.""" """Extract referenced IDs."""
if not data: if not data:
return return

View File

@ -669,10 +669,14 @@ def async_register_admin_service(
@bind_hass @bind_hass
@ha.callback @ha.callback
def verify_domain_control(hass: HomeAssistantType, domain: str) -> Callable: def verify_domain_control(
hass: HomeAssistantType, domain: str
) -> Callable[[Callable[[ha.ServiceCall], Any]], Callable[[ha.ServiceCall], Any]]:
"""Ensure permission to access any entity under domain in service call.""" """Ensure permission to access any entity under domain in service call."""
def decorator(service_handler: Callable[[ha.ServiceCall], Any]) -> Callable: def decorator(
service_handler: Callable[[ha.ServiceCall], Any]
) -> Callable[[ha.ServiceCall], Any]:
"""Decorate.""" """Decorate."""
if not asyncio.iscoroutinefunction(service_handler): if not asyncio.iscoroutinefunction(service_handler):
raise HomeAssistantError("Can only decorate async functions.") raise HomeAssistantError("Can only decorate async functions.")

View File

@ -3,7 +3,7 @@ import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging import logging
from time import monotonic from time import monotonic
from typing import Awaitable, Callable, Generic, List, Optional, TypeVar from typing import Any, Awaitable, Callable, Generic, List, Optional, TypeVar
import urllib.error import urllib.error
import aiohttp import aiohttp
@ -21,6 +21,8 @@ REQUEST_REFRESH_DEFAULT_IMMEDIATE = True
T = TypeVar("T") T = TypeVar("T")
# mypy: disallow-any-generics
class UpdateFailed(Exception): class UpdateFailed(Exception):
"""Raised when an update has failed.""" """Raised when an update has failed."""
@ -231,7 +233,7 @@ class DataUpdateCoordinator(Generic[T]):
class CoordinatorEntity(entity.Entity): class CoordinatorEntity(entity.Entity):
"""A class for entities using DataUpdateCoordinator.""" """A class for entities using DataUpdateCoordinator."""
def __init__(self, coordinator: DataUpdateCoordinator) -> None: def __init__(self, coordinator: DataUpdateCoordinator[Any]) -> None:
"""Create the entity with a DataUpdateCoordinator.""" """Create the entity with a DataUpdateCoordinator."""
self.coordinator = coordinator self.coordinator = coordinator