Add a context variable holding a HomeAssistant reference

This commit is contained in:
Erik
2022-08-05 14:01:46 +02:00
parent b366090175
commit 54f98ce447
2 changed files with 11 additions and 0 deletions

View File

@@ -187,6 +187,8 @@ async def async_setup_hass(
if runtime_config.open_ui:
hass.add_job(open_hass_ui, hass)
core._cv_hass.set(hass) # pylint: disable=protected-access
return hass

View File

@@ -15,6 +15,7 @@ from collections.abc import (
Iterable,
Mapping,
)
from contextvars import ContextVar
import datetime
import enum
import functools
@@ -138,6 +139,8 @@ MAX_EXPECTED_ENTITY_IDS = 16384
_LOGGER = logging.getLogger(__name__)
_cv_hass: ContextVar[HomeAssistant] = ContextVar("current_entry")
@functools.lru_cache(MAX_EXPECTED_ENTITY_IDS)
def split_entity_id(entity_id: str) -> tuple[str, str]:
@@ -175,6 +178,12 @@ def is_callback(func: Callable[..., Any]) -> bool:
return getattr(func, "_hass_callback", False) is True
@callback
def async_get_hass() -> HomeAssistant:
"""Return the HomeAssistant instance."""
return _cv_hass.get()
@enum.unique
class HassJobType(enum.Enum):
"""Represent a job type."""