Add async_get_hass_or_none (#118164)

This commit is contained in:
J. Nick Koston 2024-05-26 01:38:46 -10:00 committed by GitHub
parent 05c24e92d1
commit c368ffffd5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 30 additions and 44 deletions

View file

@ -27,10 +27,9 @@ from homeassistant.core import (
HassJob, HassJob,
HomeAssistant, HomeAssistant,
ServiceCall, ServiceCall,
async_get_hass, async_get_hass_or_none,
callback, callback,
) )
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import ( from homeassistant.helpers import (
config_validation as cv, config_validation as cv,
device_registry as dr, device_registry as dr,
@ -160,10 +159,7 @@ VALID_ADDON_SLUG = vol.Match(re.compile(r"^[-_.A-Za-z0-9]+$"))
def valid_addon(value: Any) -> str: def valid_addon(value: Any) -> str:
"""Validate value is a valid addon slug.""" """Validate value is a valid addon slug."""
value = VALID_ADDON_SLUG(value) value = VALID_ADDON_SLUG(value)
hass = async_get_hass_or_none()
hass: HomeAssistant | None = None
with suppress(HomeAssistantError):
hass = async_get_hass()
if hass and (addons := get_addons_info(hass)) is not None and value not in addons: if hass and (addons := get_addons_info(hass)) is not None and value not in addons:
raise vol.Invalid("Not a valid add-on slug") raise vol.Invalid("Not a valid add-on slug")

View file

@ -15,8 +15,13 @@ import voluptuous as vol
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_MODE, CONF_UNIT_OF_MEASUREMENT, UnitOfTemperature from homeassistant.const import ATTR_MODE, CONF_UNIT_OF_MEASUREMENT, UnitOfTemperature
from homeassistant.core import HomeAssistant, ServiceCall, async_get_hass, callback from homeassistant.core import (
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError HomeAssistant,
ServiceCall,
async_get_hass_or_none,
callback,
)
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.config_validation import ( from homeassistant.helpers.config_validation import (
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE, PLATFORM_SCHEMA_BASE,
@ -213,10 +218,9 @@ class NumberEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
"value", "value",
) )
): ):
hass: HomeAssistant | None = None report_issue = async_suggest_report_issue(
with suppress(HomeAssistantError): async_get_hass_or_none(), module=cls.__module__
hass = async_get_hass() )
report_issue = async_suggest_report_issue(hass, module=cls.__module__)
_LOGGER.warning( _LOGGER.warning(
( (
"%s::%s is overriding deprecated methods on an instance of " "%s::%s is overriding deprecated methods on an instance of "

View file

@ -268,8 +268,16 @@ def async_get_hass() -> HomeAssistant:
This should be used where it's very cumbersome or downright impossible to pass This should be used where it's very cumbersome or downright impossible to pass
hass to the code which needs it. hass to the code which needs it.
""" """
if not _hass.hass: if not (hass := async_get_hass_or_none()):
raise HomeAssistantError("async_get_hass called from the wrong thread") raise HomeAssistantError("async_get_hass called from the wrong thread")
return hass
def async_get_hass_or_none() -> HomeAssistant | None:
"""Return the HomeAssistant instance or None.
Returns None when called from the wrong thread.
"""
return _hass.hass return _hass.hass

View file

@ -93,8 +93,8 @@ from homeassistant.const import (
) )
from homeassistant.core import ( from homeassistant.core import (
DOMAIN as HOMEASSISTANT_DOMAIN, DOMAIN as HOMEASSISTANT_DOMAIN,
HomeAssistant,
async_get_hass, async_get_hass,
async_get_hass_or_none,
split_entity_id, split_entity_id,
valid_entity_id, valid_entity_id,
) )
@ -662,11 +662,7 @@ def template(value: Any | None) -> template_helper.Template:
if isinstance(value, (list, dict, template_helper.Template)): if isinstance(value, (list, dict, template_helper.Template)):
raise vol.Invalid("template value should be a string") raise vol.Invalid("template value should be a string")
hass: HomeAssistant | None = None template_value = template_helper.Template(str(value), async_get_hass_or_none())
with contextlib.suppress(HomeAssistantError):
hass = async_get_hass()
template_value = template_helper.Template(str(value), hass)
try: try:
template_value.ensure_valid() template_value.ensure_valid()
@ -684,11 +680,7 @@ def dynamic_template(value: Any | None) -> template_helper.Template:
if not template_helper.is_template_string(str(value)): if not template_helper.is_template_string(str(value)):
raise vol.Invalid("template value does not contain a dynamic template") raise vol.Invalid("template value does not contain a dynamic template")
hass: HomeAssistant | None = None template_value = template_helper.Template(str(value), async_get_hass_or_none())
with contextlib.suppress(HomeAssistantError):
hass = async_get_hass()
template_value = template_helper.Template(str(value), hass)
try: try:
template_value.ensure_valid() template_value.ensure_valid()

View file

@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from contextlib import suppress
from enum import Enum from enum import Enum
import functools import functools
import inspect import inspect
@ -167,8 +166,7 @@ def _print_deprecation_warning_internal(
log_when_no_integration_is_found: bool, log_when_no_integration_is_found: bool,
) -> None: ) -> None:
# pylint: disable=import-outside-toplevel # pylint: disable=import-outside-toplevel
from homeassistant.core import HomeAssistant, async_get_hass from homeassistant.core import async_get_hass_or_none
from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import async_suggest_report_issue from homeassistant.loader import async_suggest_report_issue
from .frame import MissingIntegrationFrame, get_integration_frame from .frame import MissingIntegrationFrame, get_integration_frame
@ -191,11 +189,8 @@ def _print_deprecation_warning_internal(
) )
else: else:
if integration_frame.custom_integration: if integration_frame.custom_integration:
hass: HomeAssistant | None = None
with suppress(HomeAssistantError):
hass = async_get_hass()
report_issue = async_suggest_report_issue( report_issue = async_suggest_report_issue(
hass, async_get_hass_or_none(),
integration_domain=integration_frame.integration, integration_domain=integration_frame.integration,
module=integration_frame.module, module=integration_frame.module,
) )

View file

@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio import asyncio
from collections.abc import Callable from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
import functools import functools
from functools import cached_property from functools import cached_property
@ -14,7 +13,7 @@ import sys
from types import FrameType from types import FrameType
from typing import Any, cast from typing import Any, cast
from homeassistant.core import HomeAssistant, async_get_hass from homeassistant.core import async_get_hass_or_none
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import async_suggest_report_issue from homeassistant.loader import async_suggest_report_issue
@ -176,11 +175,8 @@ def _report_integration(
return return
_REPORTED_INTEGRATIONS.add(key) _REPORTED_INTEGRATIONS.add(key)
hass: HomeAssistant | None = None
with suppress(HomeAssistantError):
hass = async_get_hass()
report_issue = async_suggest_report_issue( report_issue = async_suggest_report_issue(
hass, async_get_hass_or_none(),
integration_domain=integration_frame.integration, integration_domain=integration_frame.integration,
module=integration_frame.module, module=integration_frame.module,
) )

View file

@ -3,15 +3,13 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from contextlib import suppress
import functools import functools
import linecache import linecache
import logging import logging
import threading import threading
from typing import Any from typing import Any
from homeassistant.core import HomeAssistant, async_get_hass from homeassistant.core import async_get_hass_or_none
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.frame import ( from homeassistant.helpers.frame import (
MissingIntegrationFrame, MissingIntegrationFrame,
get_current_frame, get_current_frame,
@ -74,11 +72,8 @@ def raise_for_blocking_call(
f"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue" f"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue"
) )
hass: HomeAssistant | None = None
with suppress(HomeAssistantError):
hass = async_get_hass()
report_issue = async_suggest_report_issue( report_issue = async_suggest_report_issue(
hass, async_get_hass_or_none(),
integration_domain=integration_frame.integration, integration_domain=integration_frame.integration,
module=integration_frame.module, module=integration_frame.module,
) )