response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Validate a top level config key with an optional label and return the domain. A domain is separated from a label by one or more spaces, empty labels are not allowed. Examples: 'hue' returns 'hue' 'hue 1' returns 'hue' 'hue 1' returns 'hue' 'hue ' raises 'hue ' raises
def domain_key(config_key: Any) -> str: """Validate a top level config key with an optional label and return the domain. A domain is separated from a label by one or more spaces, empty labels are not allowed. Examples: 'hue' returns 'hue' 'hue 1' returns 'hue' 'hue 1' returns 'hue' 'hue ' raises 'hue ' raises """ if not isinstance(config_key, str): raise vol.Invalid("invalid domain", path=[config_key]) parts = config_key.partition(" ") _domain = parts[0] if parts[2].strip(" ") else config_key if not _domain or _domain.strip(" ") != _domain: raise vol.Invalid("invalid domain", path=[config_key]) return _domain
Validate that entity belong to domain.
def entity_domain(domain: str | list[str]) -> Callable[[Any], str]: """Validate that entity belong to domain.""" ent_domain = entities_domain(domain) def validate(value: str) -> str: """Test if entity domain is domain.""" validated = ent_domain(value) if len(validated) != 1: raise vol.Invalid(f"Expected exactly 1 entity, got {len(validated)}") return validated[0] return validate
Validate that entities belong to domain.
def entities_domain(domain: str | list[str]) -> Callable[[str | list], list[str]]: """Validate that entities belong to domain.""" if isinstance(domain, str): def check_invalid(val: str) -> bool: return val != domain else: def check_invalid(val: str) -> bool: return val not in domain def validate(values: str | list) -> list[str]: """Test if entity domain is domain.""" values = entity_ids(values) for ent_id in values: if check_invalid(split_entity_id(ent_id)[0]): raise vol.Invalid( f"Entity ID '{ent_id}' does not belong to domain '{domain}'" ) return values return validate
Create validator for specified enum.
def enum(enumClass: type[Enum]) -> vol.All: """Create validator for specified enum.""" return vol.All(vol.In(enumClass.__members__), enumClass.__getitem__)
Validate icon.
def icon(value: Any) -> str: """Validate icon.""" str_value = str(value) if ":" in str_value: return str_value raise vol.Invalid('Icons should be specified in the form "prefix:name"')
Validate a hex color code.
def color_hex(value: Any) -> str: """Validate a hex color code.""" str_value = str(value) if not _COLOR_HEX.match(str_value): raise vol.Invalid("Color should be in the format #RRGGBB") return str_value
Validate and transform a time.
def time(value: Any) -> time_sys: """Validate and transform a time.""" if isinstance(value, time_sys): return value try: time_val = dt_util.parse_time(value) except TypeError as err: raise vol.Invalid("Not a parseable type") from err if time_val is None: raise vol.Invalid(f"Invalid time specified: {value}") return time_val
Validate and transform a date.
def date(value: Any) -> date_sys: """Validate and transform a date.""" if isinstance(value, date_sys): return value try: date_val = dt_util.parse_date(value) except TypeError as err: raise vol.Invalid("Not a parseable type") from err if date_val is None: raise vol.Invalid("Could not parse date") return date_val
Validate and transform time offset.
def time_period_str(value: str) -> timedelta: """Validate and transform time offset.""" if isinstance(value, int): # type: ignore[unreachable] raise vol.Invalid("Make sure you wrap time values in quotes") if not isinstance(value, str): raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) negative_offset = False if value.startswith("-"): negative_offset = True value = value[1:] elif value.startswith("+"): value = value[1:] parsed = value.split(":") if len(parsed) not in (2, 3): raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) try: hour = int(parsed[0]) minute = int(parsed[1]) try: second = float(parsed[2]) except IndexError: second = 0 except ValueError as err: raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) from err offset = timedelta(hours=hour, minutes=minute, seconds=second) if negative_offset: offset *= -1 return offset
Validate and transform seconds to a time offset.
def time_period_seconds(value: float | str) -> timedelta: """Validate and transform seconds to a time offset.""" try: return timedelta(seconds=float(value)) except (ValueError, TypeError) as err: raise vol.Invalid(f"Expected seconds, got {value}") from err
Validate that matches all values.
def match_all(value: _T) -> _T: """Validate that matches all values.""" return value
Validate timedelta is positive.
def positive_timedelta(value: timedelta) -> timedelta: """Validate timedelta is positive.""" if value < timedelta(0): raise vol.Invalid("Time period should be positive") return value
Remove falsy values from a list.
def remove_falsy(value: list[_T]) -> list[_T]: """Remove falsy values from a list.""" return [v for v in value if v]
Validate service.
def service(value: Any) -> str: """Validate service.""" # Services use same format as entities so we can use same helper. str_value = string(value).lower() if valid_entity_id(str_value): return str_value raise vol.Invalid(f"Service {value} does not match format <domain>.<name>")
Validate value is a valid slug.
def slug(value: Any) -> str: """Validate value is a valid slug.""" if value is None: raise vol.Invalid("Slug should not be None") str_value = str(value) slg = util_slugify(str_value) if str_value == slg: return str_value raise vol.Invalid(f"invalid slug {value} (try {slg})")
Ensure dicts have slugs as keys. Replacement of vol.Schema({cv.slug: value_schema}) to prevent misleading "Extra keys" errors from voluptuous.
def schema_with_slug_keys( value_schema: _T | Callable, *, slug_validator: Callable[[Any], str] = slug ) -> Callable: """Ensure dicts have slugs as keys. Replacement of vol.Schema({cv.slug: value_schema}) to prevent misleading "Extra keys" errors from voluptuous. """ schema = vol.Schema({str: value_schema}) def verify(value: dict) -> dict: """Validate all keys are slugs and then the value_schema.""" if not isinstance(value, dict): raise vol.Invalid("expected dictionary") for key in value: slug_validator(key) return cast(dict, schema(value)) return verify
Coerce a value to a slug.
def slugify(value: Any) -> str: """Coerce a value to a slug.""" if value is None: raise vol.Invalid("Slug should not be None") slg = util_slugify(str(value)) if slg: return slg raise vol.Invalid(f"Unable to slugify {value}")
Coerce value to string, except for None.
def string(value: Any) -> str: """Coerce value to string, except for None.""" if value is None: raise vol.Invalid("string value is None") # This is expected to be the most common case, so check it first. if ( type(value) is str # noqa: E721 or type(value) is NodeStrClass or isinstance(value, str) ): return value if isinstance(value, template_helper.ResultWrapper): value = value.render_result elif isinstance(value, (list, dict)): raise vol.Invalid("value should be a string") return str(value)
Validate that the value is a string without HTML.
def string_with_no_html(value: Any) -> str: """Validate that the value is a string without HTML.""" value = string(value) regex = re.compile(r"<[a-z].*?>", re.IGNORECASE) if regex.search(value): raise vol.Invalid("the string should not contain HTML") return str(value)
Validate and transform temperature unit.
def temperature_unit(value: Any) -> UnitOfTemperature: """Validate and transform temperature unit.""" value = str(value).upper() if value == "C": return UnitOfTemperature.CELSIUS if value == "F": return UnitOfTemperature.FAHRENHEIT raise vol.Invalid("invalid temperature unit (expected C or F)")
Validate a jinja2 template.
def template(value: Any | None) -> template_helper.Template: """Validate a jinja2 template.""" if value is None: raise vol.Invalid("template value is None") if isinstance(value, (list, dict, template_helper.Template)): raise vol.Invalid("template value should be a string") hass: HomeAssistant | None = None with contextlib.suppress(HomeAssistantError): hass = async_get_hass() template_value = template_helper.Template(str(value), hass) try: template_value.ensure_valid() except TemplateError as ex: raise vol.Invalid(f"invalid template ({ex})") from ex return template_value
Validate a dynamic (non static) jinja2 template.
def dynamic_template(value: Any | None) -> template_helper.Template: """Validate a dynamic (non static) jinja2 template.""" if value is None: raise vol.Invalid("template value is None") if isinstance(value, (list, dict, template_helper.Template)): raise vol.Invalid("template value should be a string") if not template_helper.is_template_string(str(value)): raise vol.Invalid("template value does not contain a dynamic template") hass: HomeAssistant | None = None with contextlib.suppress(HomeAssistantError): hass = async_get_hass() template_value = template_helper.Template(str(value), hass) try: template_value.ensure_valid() except TemplateError as ex: raise vol.Invalid(f"invalid template ({ex})") from ex return template_value
Validate a complex jinja2 template.
def template_complex(value: Any) -> Any: """Validate a complex jinja2 template.""" if isinstance(value, list): return_list = value.copy() for idx, element in enumerate(return_list): return_list[idx] = template_complex(element) return return_list if isinstance(value, dict): return { template_complex(key): template_complex(element) for key, element in value.items() } if isinstance(value, str) and template_helper.is_template_string(value): return template(value) return value
Do basic validation of a positive time period expressed as a templated dict.
def _positive_time_period_template_complex(value: Any) -> Any: """Do basic validation of a positive time period expressed as a templated dict.""" if not isinstance(value, dict) or not value: raise vol.Invalid("template should be a dict") for key, element in value.items(): if not isinstance(key, str): raise vol.Invalid("key should be a string") if not template_helper.is_template_string(key): vol.In(_TIME_PERIOD_DICT_KEYS)(key) if not isinstance(element, str) or ( isinstance(element, str) and not template_helper.is_template_string(element) ): vol.All(vol.Coerce(float), vol.Range(min=0))(element) return template_complex(value)
Validate datetime.
def datetime(value: Any) -> datetime_sys: """Validate datetime.""" if isinstance(value, datetime_sys): return value try: date_val = dt_util.parse_datetime(value) except TypeError: date_val = None if date_val is None: raise vol.Invalid(f"Invalid datetime specified: {value}") return date_val
Validate timezone.
def time_zone(value: str) -> str: """Validate timezone.""" if dt_util.get_time_zone(value) is not None: return value raise vol.Invalid( "Invalid time zone passed in. Valid options can be found here: " "http://en.wikipedia.org/wiki/List_of_tz_database_time_zones" )
Validate timeout float > 0.0. None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object.
def socket_timeout(value: Any | None) -> object: """Validate timeout float > 0.0. None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object. """ if value is None: return _GLOBAL_DEFAULT_TIMEOUT try: float_value = float(value) if float_value > 0.0: return float_value raise vol.Invalid("Invalid socket timeout value. float > 0.0 required.") except Exception as err: raise vol.Invalid(f"Invalid socket timeout: {err}") from err
Validate an URL.
def url( value: Any, _schema_list: frozenset[UrlProtocolSchema] = EXTERNAL_URL_PROTOCOL_SCHEMA_LIST, ) -> str: """Validate an URL.""" url_in = str(value) if urlparse(url_in).scheme in _schema_list: return cast(str, vol.Schema(vol.Url())(url_in)) raise vol.Invalid("invalid url")
Validate an URL that allows the homeassistant schema.
def configuration_url(value: Any) -> str: """Validate an URL that allows the homeassistant schema.""" return url(value, CONFIGURATION_URL_PROTOCOL_SCHEMA_LIST)
Validate a url without a path.
def url_no_path(value: Any) -> str: """Validate a url without a path.""" url_in = url(value) if urlparse(url_in).path not in ("", "/"): raise vol.Invalid("url it not allowed to have a path component") return url_in
Validate an x10 address.
def x10_address(value: str) -> str: """Validate an x10 address.""" regex = re.compile(r"([A-Pa-p]{1})(?:[2-9]|1[0-6]?)$") if not regex.match(value): raise vol.Invalid("Invalid X10 Address") return str(value).lower()
Validate a v4 UUID in hex format.
def uuid4_hex(value: Any) -> str: """Validate a v4 UUID in hex format.""" try: result = UUID(value, version=4) except (ValueError, AttributeError, TypeError) as error: raise vol.Invalid("Invalid Version4 UUID", error_message=str(error)) from error if result.hex != value.lower(): # UUID() will create a uuid4 if input is invalid raise vol.Invalid("Invalid Version4 UUID") return result.hex
Validate a fake v4 UUID generated by random_uuid_hex.
def fake_uuid4_hex(value: Any) -> str: """Validate a fake v4 UUID generated by random_uuid_hex.""" try: if not _FAKE_UUID_4_HEX.match(value): raise vol.Invalid("Invalid UUID") except TypeError as exc: raise vol.Invalid("Invalid UUID") from exc return cast(str, value)
Ensure that input is a list or make one from comma-separated string.
def ensure_list_csv(value: Any) -> list: """Ensure that input is a list or make one from comma-separated string.""" if isinstance(value, str): return [member.strip() for member in value.split(",")] return ensure_list(value)
Log key as deprecated and provide a replacement (if exists) or fail. Expected behavior: - Outputs or throws the appropriate deprecation warning if key is detected - Outputs or throws the appropriate error if key is detected and removed from support - Processes schema moving the value from key to replacement_key - Processes schema changing nothing if only replacement_key provided - No warning if only replacement_key provided - No warning if neither key nor replacement_key are provided - Adds replacement_key with default value in this case
def _deprecated_or_removed( key: str, replacement_key: str | None, default: Any | None, raise_if_present: bool, option_removed: bool, ) -> Callable[[dict], dict]: """Log key as deprecated and provide a replacement (if exists) or fail. Expected behavior: - Outputs or throws the appropriate deprecation warning if key is detected - Outputs or throws the appropriate error if key is detected and removed from support - Processes schema moving the value from key to replacement_key - Processes schema changing nothing if only replacement_key provided - No warning if only replacement_key provided - No warning if neither key nor replacement_key are provided - Adds replacement_key with default value in this case """ def validator(config: dict) -> dict: """Check if key is in config and log warning or error.""" if key in config: if option_removed: level = logging.ERROR option_status = "has been removed" else: level = logging.WARNING option_status = "is deprecated" try: near = ( f"near {config.__config_file__}" # type: ignore[attr-defined] f":{config.__line__} " # type: ignore[attr-defined] ) except AttributeError: near = "" arguments: tuple[str, ...] if replacement_key: warning = "The '%s' option %s%s, please replace it with '%s'" arguments = (key, near, option_status, replacement_key) else: warning = ( "The '%s' option %s%s, please remove it from your configuration" ) arguments = (key, near, option_status) if raise_if_present: raise vol.Invalid(warning % arguments) get_integration_logger(__name__).log(level, warning, *arguments) value = config[key] if replacement_key or option_removed: config.pop(key) else: value = default keys = [key] if replacement_key: keys.append(replacement_key) if value is not None and ( replacement_key not in config or default == config.get(replacement_key) ): config[replacement_key] = value return has_at_most_one_key(*keys)(config) return validator
Log key as deprecated and provide a replacement (if exists). Expected behavior: - Outputs the appropriate deprecation warning if key is detected or raises an exception - Processes schema moving the value from key to replacement_key - Processes schema changing nothing if only replacement_key provided - No warning if only replacement_key provided - No warning if neither key nor replacement_key are provided - Adds replacement_key with default value in this case
def deprecated( key: str, replacement_key: str | None = None, default: Any | None = None, raise_if_present: bool | None = False, ) -> Callable[[dict], dict]: """Log key as deprecated and provide a replacement (if exists). Expected behavior: - Outputs the appropriate deprecation warning if key is detected or raises an exception - Processes schema moving the value from key to replacement_key - Processes schema changing nothing if only replacement_key provided - No warning if only replacement_key provided - No warning if neither key nor replacement_key are provided - Adds replacement_key with default value in this case """ return _deprecated_or_removed( key, replacement_key=replacement_key, default=default, raise_if_present=raise_if_present or False, option_removed=False, )
Log key as deprecated and fail the config validation. Expected behavior: - Outputs the appropriate error if key is detected and removed from support or raises an exception.
def removed( key: str, default: Any | None = None, raise_if_present: bool | None = True, ) -> Callable[[dict], dict]: """Log key as deprecated and fail the config validation. Expected behavior: - Outputs the appropriate error if key is detected and removed from support or raises an exception. """ return _deprecated_or_removed( key, replacement_key=None, default=default, raise_if_present=raise_if_present or False, option_removed=True, )
Create a validator that validates based on a value for specific key. This gives better error messages.
def key_value_schemas( key: str, value_schemas: dict[Hashable, vol.Schema], default_schema: vol.Schema | None = None, default_description: str | None = None, ) -> Callable[[Any], dict[Hashable, Any]]: """Create a validator that validates based on a value for specific key. This gives better error messages. """ def key_value_validator(value: Any) -> dict[Hashable, Any]: if not isinstance(value, dict): raise vol.Invalid("Expected a dictionary") key_value = value.get(key) if isinstance(key_value, Hashable) and key_value in value_schemas: return cast(dict[Hashable, Any], value_schemas[key_value](value)) if default_schema: with contextlib.suppress(vol.Invalid): return cast(dict[Hashable, Any], default_schema(value)) alternatives = ", ".join(str(alternative) for alternative in value_schemas) if default_description: alternatives = f"{alternatives}, {default_description}" raise vol.Invalid( f"Unexpected value for {key}: '{key_value}'. Expected {alternatives}" ) return key_value_validator
Validate that all dependencies exist for key.
def key_dependency( key: Hashable, dependency: Hashable ) -> Callable[[dict[Hashable, Any]], dict[Hashable, Any]]: """Validate that all dependencies exist for key.""" def validator(value: dict[Hashable, Any]) -> dict[Hashable, Any]: """Test dependencies.""" if not isinstance(value, dict): raise vol.Invalid("key dependencies require a dict") if key in value and dependency not in value: raise vol.Invalid( f'dependency violation - key "{key}" requires ' f'key "{dependency}" to exist' ) return value return validator
Serialize additional types for voluptuous_serialize.
def custom_serializer(schema: Any) -> Any: """Serialize additional types for voluptuous_serialize.""" from . import selector # pylint: disable=import-outside-toplevel if schema is positive_time_period_dict: return {"type": "positive_time_period_dict"} if schema is string: return {"type": "string"} if schema is boolean: return {"type": "boolean"} if isinstance(schema, multi_select): return {"type": "multi_select", "options": schema.options} if isinstance(schema, selector.Selector): return schema.serialize() return voluptuous_serialize.UNSUPPORTED
Expand boolean condition shorthand notations.
def expand_condition_shorthand(value: Any | None) -> Any: """Expand boolean condition shorthand notations.""" if not isinstance(value, dict) or CONF_CONDITIONS in value: return value for key, schema in ( ("and", AND_CONDITION_SHORTHAND_SCHEMA), ("or", OR_CONDITION_SHORTHAND_SCHEMA), ("not", NOT_CONDITION_SHORTHAND_SCHEMA), ): try: schema(value) return { CONF_CONDITION: key, CONF_CONDITIONS: value[key], **{k: value[k] for k in value if k != key}, } except vol.MultipleInvalid: pass if isinstance(value.get(CONF_CONDITION), list): try: CONDITION_SHORTHAND_SCHEMA(value) return { CONF_CONDITION: "and", CONF_CONDITIONS: value[CONF_CONDITION], **{k: value[k] for k in value if k != CONF_CONDITION}, } except vol.MultipleInvalid: pass return value
Return a config schema which logs if there are configuration parameters.
def empty_config_schema(domain: str) -> Callable[[dict], dict]: """Return a config schema which logs if there are configuration parameters.""" def validator(config: dict) -> dict: if config_domain := config.get(domain): get_integration_logger(__name__).error( ( "The %s integration does not support any configuration parameters, " "got %s. Please remove the configuration parameters from your " "configuration." ), domain, config_domain, ) return config return validator
Return a config schema which logs if attempted to setup from YAML.
def _no_yaml_config_schema( domain: str, issue_base: str, translation_key: str, translation_placeholders: dict[str, str], ) -> Callable[[dict], dict]: """Return a config schema which logs if attempted to setup from YAML.""" def raise_issue() -> None: # pylint: disable-next=import-outside-toplevel from .issue_registry import IssueSeverity, async_create_issue # HomeAssistantError is raised if called from the wrong thread with contextlib.suppress(HomeAssistantError): hass = async_get_hass() async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"{issue_base}_{domain}", is_fixable=False, issue_domain=domain, severity=IssueSeverity.ERROR, translation_key=translation_key, translation_placeholders={"domain": domain} | translation_placeholders, ) def validator(config: dict) -> dict: if domain in config: get_integration_logger(__name__).error( ( "The %s integration does not support YAML setup, please remove it " "from your configuration file" ), domain, ) raise_issue() return config return validator
Return a config schema which logs if attempted to setup from YAML. Use this when an integration's __init__.py defines setup or async_setup but setup from yaml is not supported.
def config_entry_only_config_schema(domain: str) -> Callable[[dict], dict]: """Return a config schema which logs if attempted to setup from YAML. Use this when an integration's __init__.py defines setup or async_setup but setup from yaml is not supported. """ return _no_yaml_config_schema( domain, "config_entry_only", "config_entry_only", {"add_integration": f"/config/integrations/dashboard/add?domain={domain}"}, )
Return a config schema which logs if attempted to setup from YAML. Use this when an integration's __init__.py defines setup or async_setup but setup from the integration key is not supported.
def platform_only_config_schema(domain: str) -> Callable[[dict], dict]: """Return a config schema which logs if attempted to setup from YAML. Use this when an integration's __init__.py defines setup or async_setup but setup from the integration key is not supported. """ return _no_yaml_config_schema( domain, "platform_only", "platform_only", {}, )
Create an entity service schema.
def _make_entity_service_schema(schema: dict, extra: int) -> vol.Schema: """Create an entity service schema.""" return vol.Schema( vol.All( vol.Schema( { # The frontend stores data here. Don't use in core. vol.Remove("metadata"): dict, **schema, **ENTITY_SERVICE_FIELDS, }, extra=extra, ), _HAS_ENTITY_SERVICE_FIELD, ) )
Create an entity service schema.
def make_entity_service_schema( schema: dict, *, extra: int = vol.PREVENT_EXTRA ) -> vol.Schema: """Create an entity service schema.""" if not schema and extra == vol.PREVENT_EXTRA: # If the schema is empty and we don't allow extra keys, we can return # the base schema and avoid compiling a new schema which is the case # for ~50% of services. return BASE_ENTITY_SCHEMA return _make_entity_service_schema(schema, extra)
Validate a script action.
def script_action(value: Any) -> dict: """Validate a script action.""" if not isinstance(value, dict): raise vol.Invalid("expected dictionary") try: action = determine_script_action(value) except ValueError as err: raise vol.Invalid(str(err)) from err return ACTION_TYPE_SCHEMAS[action](value)
Validate a state condition.
def STATE_CONDITION_SCHEMA(value: Any) -> dict: """Validate a state condition.""" if not isinstance(value, dict): raise vol.Invalid("Expected a dictionary") if CONF_ATTRIBUTE in value: validated: dict = STATE_CONDITION_ATTRIBUTE_SCHEMA(value) else: validated = STATE_CONDITION_STATE_SCHEMA(value) return key_dependency("for", "state")(validated)
Determine action type.
def determine_script_action(action: dict[str, Any]) -> str: """Determine action type.""" if not (actions := ACTIONS_SET.intersection(action)): raise ValueError("Unable to determine action") if len(actions) > 1: # Ambiguous action, select the first one in the # order of the ACTIONS_MAP for action_key, _script_action in ACTIONS_MAP.items(): if action_key in actions: return _script_action return ACTIONS_MAP[actions.pop()]
Help migrate properties to new names. When a property is added to replace an older property, this decorator can be added to the new property, listing the old property as the substitute. If the old property is defined, its value will be used instead, and a log warning will be issued alerting the user of the impending change.
def deprecated_substitute( substitute_name: str, ) -> Callable[[Callable[[_ObjectT], Any]], Callable[[_ObjectT], Any]]: """Help migrate properties to new names. When a property is added to replace an older property, this decorator can be added to the new property, listing the old property as the substitute. If the old property is defined, its value will be used instead, and a log warning will be issued alerting the user of the impending change. """ def decorator(func: Callable[[_ObjectT], Any]) -> Callable[[_ObjectT], Any]: """Decorate function as deprecated.""" def func_wrapper(self: _ObjectT) -> Any: """Wrap for the original function.""" if hasattr(self, substitute_name): # If this platform is still using the old property, issue # a logger warning once with instructions on how to fix it. warnings = getattr(func, "_deprecated_substitute_warnings", {}) module_name = self.__module__ if not warnings.get(module_name): logger = logging.getLogger(module_name) logger.warning( ( "'%s' is deprecated. Please rename '%s' to " "'%s' in '%s' to ensure future support." ), substitute_name, substitute_name, func.__name__, inspect.getfile(self.__class__), ) warnings[module_name] = True setattr(func, "_deprecated_substitute_warnings", warnings) # Return the old property return getattr(self, substitute_name) return func(self) return func_wrapper return decorator
Allow an old config name to be deprecated with a replacement. If the new config isn't found, but the old one is, the old value is used and a warning is issued to the user.
def get_deprecated( config: dict[str, Any], new_name: str, old_name: str, default: Any | None = None ) -> Any | None: """Allow an old config name to be deprecated with a replacement. If the new config isn't found, but the old one is, the old value is used and a warning is issued to the user. """ if old_name in config: module = inspect.getmodule(inspect.stack(context=0)[1].frame) if module is not None: module_name = module.__name__ else: # If Python is unable to access the sources files, the call stack frame # will be missing information, so let's guard. # https://github.com/home-assistant/core/issues/24982 module_name = __name__ logger = logging.getLogger(module_name) logger.warning( ( "'%s' is deprecated. Please rename '%s' to '%s' in your " "configuration file." ), old_name, old_name, new_name, ) return config.get(old_name) return config.get(new_name, default)
Mark class as deprecated and provide a replacement class to be used instead. If the deprecated function was called from a custom integration, ask the user to report an issue.
def deprecated_class( replacement: str, *, breaks_in_ha_version: str | None = None ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: """Mark class as deprecated and provide a replacement class to be used instead. If the deprecated function was called from a custom integration, ask the user to report an issue. """ def deprecated_decorator(cls: Callable[_P, _R]) -> Callable[_P, _R]: """Decorate class as deprecated.""" @functools.wraps(cls) def deprecated_cls(*args: _P.args, **kwargs: _P.kwargs) -> _R: """Wrap for the original class.""" _print_deprecation_warning( cls, replacement, "class", "instantiated", breaks_in_ha_version ) return cls(*args, **kwargs) return deprecated_cls return deprecated_decorator
Mark function as deprecated and provide a replacement to be used instead. If the deprecated function was called from a custom integration, ask the user to report an issue.
def deprecated_function( replacement: str, *, breaks_in_ha_version: str | None = None ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: """Mark function as deprecated and provide a replacement to be used instead. If the deprecated function was called from a custom integration, ask the user to report an issue. """ def deprecated_decorator(func: Callable[_P, _R]) -> Callable[_P, _R]: """Decorate function as deprecated.""" @functools.wraps(func) def deprecated_func(*args: _P.args, **kwargs: _P.kwargs) -> _R: """Wrap for the original function.""" _print_deprecation_warning( func, replacement, "function", "called", breaks_in_ha_version ) return func(*args, **kwargs) return deprecated_func return deprecated_decorator
Check if the not found name is a deprecated constant. If it is, print a deprecation warning and return the value of the constant. Otherwise raise AttributeError.
def check_if_deprecated_constant(name: str, module_globals: dict[str, Any]) -> Any: """Check if the not found name is a deprecated constant. If it is, print a deprecation warning and return the value of the constant. Otherwise raise AttributeError. """ module_name = module_globals.get("__name__") value = replacement = None description = "constant" if (deprecated_const := module_globals.get(_PREFIX_DEPRECATED + name)) is None: raise AttributeError(f"Module {module_name!r} has no attribute {name!r}") if isinstance(deprecated_const, DeprecatedConstant): value = deprecated_const.value replacement = deprecated_const.replacement breaks_in_ha_version = deprecated_const.breaks_in_ha_version elif isinstance(deprecated_const, DeprecatedConstantEnum): value = deprecated_const.enum.value replacement = ( f"{deprecated_const.enum.__class__.__name__}.{deprecated_const.enum.name}" ) breaks_in_ha_version = deprecated_const.breaks_in_ha_version elif isinstance(deprecated_const, DeprecatedAlias): description = "alias" value = deprecated_const.value replacement = deprecated_const.replacement breaks_in_ha_version = deprecated_const.breaks_in_ha_version if value is None or replacement is None: msg = ( f"Value of {_PREFIX_DEPRECATED}{name} is an instance of {type(deprecated_const)} " "but an instance of DeprecatedConstant or DeprecatedConstantEnum is required" ) logging.getLogger(module_name).debug(msg) # PEP 562 -- Module __getattr__ and __dir__ # specifies that __getattr__ should raise AttributeError if the attribute is not # found. # https://peps.python.org/pep-0562/#specification raise AttributeError(msg) _print_deprecation_warning_internal( name, module_name or __name__, replacement, description, "used", breaks_in_ha_version, log_when_no_integration_is_found=False, ) return value
Return dir() with deprecated constants.
def dir_with_deprecated_constants(module_globals_keys: list[str]) -> list[str]: """Return dir() with deprecated constants.""" return module_globals_keys + [ name.removeprefix(_PREFIX_DEPRECATED) for name in module_globals_keys if name.startswith(_PREFIX_DEPRECATED) ]
Generate a list for __all___ with deprecated constants.
def all_with_deprecated_constants(module_globals: dict[str, Any]) -> list[str]: """Generate a list for __all___ with deprecated constants.""" # Iterate over a copy in case the globals dict is mutated by another thread # while we loop over it. module_globals_keys = list(module_globals) return [itm for itm in module_globals_keys if not itm.startswith("_")] + [ name.removeprefix(_PREFIX_DEPRECATED) for name in module_globals_keys if name.startswith(_PREFIX_DEPRECATED) ]
Process a device info.
def _validate_device_info( config_entry: ConfigEntry, device_info: DeviceInfo, ) -> str: """Process a device info.""" keys = set(device_info) # If no keys or not enough info to match up, abort if not device_info.get("connections") and not device_info.get("identifiers"): raise DeviceInfoError( config_entry.domain, device_info, "device info must include at least one of identifiers or connections", ) device_info_type: str | None = None # Find the first device info type which has all keys in the device info for possible_type, allowed_keys in DEVICE_INFO_TYPES.items(): if keys <= allowed_keys: device_info_type = possible_type break if device_info_type is None: raise DeviceInfoError( config_entry.domain, device_info, ( "device info needs to either describe a device, " "link to existing device or provide extra information." ), ) return device_info_type
Validate and convert configuration_url.
def _validate_configuration_url(value: Any) -> str | None: """Validate and convert configuration_url.""" if value is None: return None url_as_str = str(value) url = value if type(value) is URL else _cached_parse_url(url_as_str) if url.scheme not in CONFIGURATION_URL_SCHEMES or not url.host: raise ValueError(f"invalid configuration_url '{value}'") return url_as_str
Format the mac address string for entry into dev reg.
def format_mac(mac: str) -> str: """Format the mac address string for entry into dev reg.""" to_test = mac if len(to_test) == 17 and to_test.count(":") == 5: return to_test.lower() if len(to_test) == 17 and to_test.count("-") == 5: to_test = to_test.replace("-", "") elif len(to_test) == 14 and to_test.count(".") == 2: to_test = to_test.replace(".", "") if len(to_test) == 12: # no : included return ":".join(to_test.lower()[i : i + 2] for i in range(0, 12, 2)) # Not sure how formatted, return original return mac
Get device registry.
def async_get(hass: HomeAssistant) -> DeviceRegistry: """Get device registry.""" return cast(DeviceRegistry, hass.data[DATA_REGISTRY])
Return entries that match an area.
def async_entries_for_area(registry: DeviceRegistry, area_id: str) -> list[DeviceEntry]: """Return entries that match an area.""" return registry.devices.get_devices_for_area_id(area_id)
Return entries that match a label.
def async_entries_for_label( registry: DeviceRegistry, label_id: str ) -> list[DeviceEntry]: """Return entries that match a label.""" return registry.devices.get_devices_for_label(label_id)
Return entries that match a config entry.
def async_entries_for_config_entry( registry: DeviceRegistry, config_entry_id: str ) -> list[DeviceEntry]: """Return entries that match a config entry.""" return registry.devices.get_devices_for_config_entry_id(config_entry_id)
Handle a config entry being disabled or enabled. Disable devices in the registry that are associated with a config entry when the config entry is disabled, enable devices in the registry that are associated with a config entry when the config entry is enabled and the devices are marked DeviceEntryDisabler.CONFIG_ENTRY. Only disable a device if all associated config entries are disabled.
def async_config_entry_disabled_by_changed( registry: DeviceRegistry, config_entry: ConfigEntry ) -> None: """Handle a config entry being disabled or enabled. Disable devices in the registry that are associated with a config entry when the config entry is disabled, enable devices in the registry that are associated with a config entry when the config entry is enabled and the devices are marked DeviceEntryDisabler.CONFIG_ENTRY. Only disable a device if all associated config entries are disabled. """ devices = async_entries_for_config_entry(registry, config_entry.entry_id) if not config_entry.disabled_by: for device in devices: if device.disabled_by is not DeviceEntryDisabler.CONFIG_ENTRY: continue registry.async_update_device(device.id, disabled_by=None) return enabled_config_entries = { entry.entry_id for entry in registry.hass.config_entries.async_entries() if not entry.disabled_by } for device in devices: if device.disabled: # Device already disabled, do not overwrite continue if len(device.config_entries) > 1 and device.config_entries.intersection( enabled_config_entries ): continue registry.async_update_device( device.id, disabled_by=DeviceEntryDisabler.CONFIG_ENTRY )
Clean up device registry.
def async_cleanup( hass: HomeAssistant, dev_reg: DeviceRegistry, ent_reg: entity_registry.EntityRegistry, ) -> None: """Clean up device registry.""" # Find all devices that are referenced by a config_entry. config_entry_ids = set(hass.config_entries.async_entry_ids()) references_config_entries = { device.id for device in dev_reg.devices.values() for config_entry_id in device.config_entries if config_entry_id in config_entry_ids } # Find all devices that are referenced in the entity registry. device_ids_referenced_by_entities = set(ent_reg.entities.get_device_ids()) orphan = ( set(dev_reg.devices) - device_ids_referenced_by_entities - references_config_entries ) for dev_id in orphan: dev_reg.async_remove_device(dev_id) # Find all referenced config entries that no longer exist # This shouldn't happen but have not been able to track down the bug :( for device in list(dev_reg.devices.values()): for config_entry_id in device.config_entries: if config_entry_id not in config_entry_ids: dev_reg.async_update_device( device.id, remove_config_entry_id=config_entry_id ) # Periodic purge of orphaned devices to avoid the registry # growing without bounds when there are lots of deleted devices dev_reg.async_purge_expired_orphaned_devices()
Clean up device registry when entities removed.
def async_setup_cleanup(hass: HomeAssistant, dev_reg: DeviceRegistry) -> None: """Clean up device registry when entities removed.""" # pylint: disable-next=import-outside-toplevel from . import entity_registry, label_registry as lr @callback def _label_removed_from_registry_filter( event_data: lr.EventLabelRegistryUpdatedData, ) -> bool: """Filter all except for the remove action from label registry events.""" return event_data["action"] == "remove" @callback def _handle_label_registry_update(event: lr.EventLabelRegistryUpdated) -> None: """Update devices that have a label that has been removed.""" dev_reg.async_clear_label_id(event.data["label_id"]) hass.bus.async_listen( event_type=lr.EVENT_LABEL_REGISTRY_UPDATED, event_filter=_label_removed_from_registry_filter, listener=_handle_label_registry_update, ) @callback def _async_cleanup() -> None: """Cleanup.""" ent_reg = entity_registry.async_get(hass) async_cleanup(hass, dev_reg, ent_reg) debounced_cleanup: Debouncer[None] = Debouncer( hass, _LOGGER, cooldown=CLEANUP_DELAY, immediate=False, function=_async_cleanup ) @callback def _async_entity_registry_changed( event: Event[entity_registry.EventEntityRegistryUpdatedData], ) -> None: """Handle entity updated or removed dispatch.""" debounced_cleanup.async_schedule_call() @callback def entity_registry_changed_filter( event_data: entity_registry.EventEntityRegistryUpdatedData, ) -> bool: """Handle entity updated or removed filter.""" if ( event_data["action"] == "update" and "device_id" not in event_data["changes"] ) or event_data["action"] == "create": return False return True def _async_listen_for_cleanup() -> None: """Listen for entity registry changes.""" hass.bus.async_listen( entity_registry.EVENT_ENTITY_REGISTRY_UPDATED, _async_entity_registry_changed, event_filter=entity_registry_changed_filter, ) if hass.is_running: _async_listen_for_cleanup() return async def startup_clean(event: Event) -> None: """Clean up on startup.""" _async_listen_for_cleanup() await debounced_cleanup.async_call() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, startup_clean) @callback def _on_homeassistant_stop(event: Event) -> None: """Cancel debounced cleanup.""" debounced_cleanup.async_cancel() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _on_homeassistant_stop)
Normalize connections to ensure we can match mac addresses.
def _normalize_connections(connections: set[tuple[str, str]]) -> set[tuple[str, str]]: """Normalize connections to ensure we can match mac addresses.""" return { (key, format_mac(value)) if key == CONNECTION_NETWORK_MAC else (key, value) for key, value in connections }
Set up listener for discovery of specific service. Service can be a string or a list/tuple.
def async_listen( hass: core.HomeAssistant, service: str, callback: Callable[ [str, DiscoveryInfoType | None], Coroutine[Any, Any, None] | None ], ) -> None: """Set up listener for discovery of specific service. Service can be a string or a list/tuple. """ job = core.HassJob(callback, f"discovery listener {service}") @core.callback def _async_discovery_event_listener(discovered: DiscoveryDict) -> None: """Listen for discovery events.""" hass.async_run_hass_job(job, discovered["service"], discovered["discovered"]) async_dispatcher_connect( hass, SIGNAL_PLATFORM_DISCOVERED.format(service), _async_discovery_event_listener, )
Fire discovery event. Can ensure a component is loaded.
def discover( hass: core.HomeAssistant, service: str, discovered: DiscoveryInfoType, component: str, hass_config: ConfigType, ) -> None: """Fire discovery event. Can ensure a component is loaded.""" hass.create_task( async_discover(hass, service, discovered, component, hass_config), f"discover {service} {component} {discovered}", )
Register a platform loader listener. This method must be run in the event loop.
def async_listen_platform( hass: core.HomeAssistant, component: str, callback: Callable[[str, dict[str, Any] | None], Any], ) -> Callable[[], None]: """Register a platform loader listener. This method must be run in the event loop. """ service = EVENT_LOAD_PLATFORM.format(component) job = core.HassJob(callback, f"platform loaded {component}") @core.callback def _async_discovery_platform_listener(discovered: DiscoveryDict) -> None: """Listen for platform discovery events.""" if not (platform := discovered["platform"]): return hass.async_run_hass_job(job, platform, discovered.get("discovered")) return async_dispatcher_connect( hass, SIGNAL_PLATFORM_DISCOVERED.format(service), _async_discovery_platform_listener, )
Load a component and platform dynamically.
def load_platform( hass: core.HomeAssistant, component: Platform | str, platform: str, discovered: DiscoveryInfoType | None, hass_config: ConfigType, ) -> None: """Load a component and platform dynamically.""" hass.create_task( async_load_platform(hass, component, platform, discovered, hass_config), f"discovery load_platform {component} {platform}", )
Create a discovery flow.
def async_create_flow( hass: HomeAssistant, domain: str, context: dict[str, Any], data: Any ) -> None: """Create a discovery flow.""" dispatcher: FlowDispatcher | None = None if DISCOVERY_FLOW_DISPATCHER in hass.data: dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER] elif hass.state is not CoreState.running: dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER] = FlowDispatcher(hass) dispatcher.async_setup() if not dispatcher or dispatcher.started: if init_coro := _async_init_flow(hass, domain, context, data): hass.async_create_background_task( init_coro, f"discovery flow {domain} {context}", eager_start=True ) return return dispatcher.async_create(domain, context, data)
Create a discovery flow.
def _async_init_flow( hass: HomeAssistant, domain: str, context: dict[str, Any], data: Any ) -> Coroutine[None, None, ConfigFlowResult] | None: """Create a discovery flow.""" # Avoid spawning flows that have the same initial discovery data # as ones in progress as it may cause additional device probing # which can overload devices since zeroconf/ssdp updates can happen # multiple times in the same minute if ( hass.config_entries.flow.async_has_matching_flow(domain, context, data) or hass.is_stopping ): return None return hass.config_entries.flow.async_init(domain, context=context, data=data)
Connect a callable function to a signal.
def dispatcher_connect( hass: HomeAssistant, signal: SignalType[*_Ts], target: Callable[[*_Ts], None], ) -> Callable[[], None]: """Connect a callable function to a signal.""" async_unsub = run_callback_threadsafe( hass.loop, async_dispatcher_connect, hass, signal, target ).result() def remove_dispatcher() -> None: """Remove signal listener.""" run_callback_threadsafe(hass.loop, async_unsub).result() return remove_dispatcher
Remove signal listener.
def _async_remove_dispatcher( dispatchers: _DispatcherDataType[*_Ts], signal: SignalType[*_Ts] | str, target: Callable[[*_Ts], Any] | Callable[..., Any], ) -> None: """Remove signal listener.""" try: signal_dispatchers = dispatchers[signal] del signal_dispatchers[target] # Cleanup the signal dict if it is now empty # to prevent memory leaks if not signal_dispatchers: del dispatchers[signal] except (KeyError, ValueError): # KeyError is key target listener did not exist # ValueError if listener did not exist within signal _LOGGER.warning("Unable to remove unknown dispatcher %s", target)
Connect a callable function to a signal. This method must be run in the event loop.
def async_dispatcher_connect( hass: HomeAssistant, signal: SignalType[*_Ts] | str, target: Callable[[*_Ts], Any] | Callable[..., Any], ) -> Callable[[], None]: """Connect a callable function to a signal. This method must be run in the event loop. """ if DATA_DISPATCHER not in hass.data: hass.data[DATA_DISPATCHER] = {} dispatchers: _DispatcherDataType[*_Ts] = hass.data[DATA_DISPATCHER] if signal not in dispatchers: dispatchers[signal] = {} dispatchers[signal][target] = None # Use a partial for the remove since it uses # less memory than a full closure since a partial copies # the body of the function and we don't have to store # many different copies of the same function return partial(_async_remove_dispatcher, dispatchers, signal, target)
Send signal and data.
def dispatcher_send(hass: HomeAssistant, signal: SignalType[*_Ts], *args: *_Ts) -> None: """Send signal and data.""" hass.loop.call_soon_threadsafe(async_dispatcher_send, hass, signal, *args)
Format error message.
def _format_err( signal: SignalType[*_Ts] | str, target: Callable[[*_Ts], Any] | Callable[..., Any], *args: Any, ) -> str: """Format error message.""" return "Exception in {} when dispatching '{}': {}".format( # Functions wrapped in partial do not have a __name__ getattr(target, "__name__", None) or str(target), signal, args, )
Generate a HassJob for a signal and target.
def _generate_job( signal: SignalType[*_Ts] | str, target: Callable[[*_Ts], Any] | Callable[..., Any] ) -> HassJob[..., None | Coroutine[Any, Any, None]]: """Generate a HassJob for a signal and target.""" job_type = get_hassjob_callable_job_type(target) return HassJob( catch_log_exception( target, partial(_format_err, signal, target), job_type=job_type ), f"dispatcher {signal}", job_type=job_type, )
Send signal and data. This method must be run in the event loop.
def async_dispatcher_send( hass: HomeAssistant, signal: SignalType[*_Ts] | str, *args: *_Ts ) -> None: """Send signal and data. This method must be run in the event loop. """ if hass.config.debug: hass.verify_event_loop_thread("async_dispatcher_send") if (maybe_dispatchers := hass.data.get(DATA_DISPATCHER)) is None: return dispatchers: _DispatcherDataType[*_Ts] = maybe_dispatchers if (target_list := dispatchers.get(signal)) is None: return for target, job in list(target_list.items()): if job is None: job = _generate_job(signal, target) target_list[target] = job hass.async_run_hass_job(job, *args)
Set up entity sources.
def async_setup(hass: HomeAssistant) -> None: """Set up entity sources.""" entity_sources(hass)
Get the entity sources.
def entity_sources(hass: HomeAssistant) -> dict[str, EntityInfo]: """Get the entity sources.""" return {}
Generate a unique entity ID based on given entity IDs or used IDs.
def generate_entity_id( entity_id_format: str, name: str | None, current_ids: list[str] | None = None, hass: HomeAssistant | None = None, ) -> str: """Generate a unique entity ID based on given entity IDs or used IDs.""" return async_generate_entity_id(entity_id_format, name, current_ids, hass)
Generate a unique entity ID based on given entity IDs or used IDs.
def async_generate_entity_id( entity_id_format: str, name: str | None, current_ids: Iterable[str] | None = None, hass: HomeAssistant | None = None, ) -> str: """Generate a unique entity ID based on given entity IDs or used IDs.""" name = (name or DEVICE_DEFAULT_NAME).lower() preferred_string = entity_id_format.format(slugify(name)) if current_ids is not None: return ensure_unique_string(preferred_string, current_ids) if hass is None: raise ValueError("Missing required parameter current_ids or hass") test_string = preferred_string tries = 1 while not hass.states.async_available(test_string): tries += 1 test_string = f"{preferred_string}_{tries}" return test_string
Get a capability attribute of an entity. First try the statemachine, then entity registry.
def get_capability(hass: HomeAssistant, entity_id: str, capability: str) -> Any | None: """Get a capability attribute of an entity. First try the statemachine, then entity registry. """ if state := hass.states.get(entity_id): return state.attributes.get(capability) entity_registry = er.async_get(hass) if not (entry := entity_registry.async_get(entity_id)): raise HomeAssistantError(f"Unknown entity {entity_id}") return entry.capabilities.get(capability) if entry.capabilities else None
Get device class of an entity. First try the statemachine, then entity registry.
def get_device_class(hass: HomeAssistant, entity_id: str) -> str | None: """Get device class of an entity. First try the statemachine, then entity registry. """ if state := hass.states.get(entity_id): return state.attributes.get(ATTR_DEVICE_CLASS) entity_registry = er.async_get(hass) if not (entry := entity_registry.async_get(entity_id)): raise HomeAssistantError(f"Unknown entity {entity_id}") return entry.device_class or entry.original_device_class
Get supported features for an entity. First try the statemachine, then entity registry.
def get_supported_features(hass: HomeAssistant, entity_id: str) -> int: """Get supported features for an entity. First try the statemachine, then entity registry. """ if state := hass.states.get(entity_id): return state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) # type: ignore[no-any-return] entity_registry = er.async_get(hass) if not (entry := entity_registry.async_get(entity_id)): raise HomeAssistantError(f"Unknown entity {entity_id}") return entry.supported_features or 0
Get unit of measurement of an entity. First try the statemachine, then entity registry.
def get_unit_of_measurement(hass: HomeAssistant, entity_id: str) -> str | None: """Get unit of measurement of an entity. First try the statemachine, then entity registry. """ if state := hass.states.get(entity_id): return state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) entity_registry = er.async_get(hass) if not (entry := entity_registry.async_get(entity_id)): raise HomeAssistantError(f"Unknown entity {entity_id}") return entry.unit_of_measurement
Convert the filter schema into a filter.
def convert_filter(config: dict[str, list[str]]) -> EntityFilter: """Convert the filter schema into a filter.""" return EntityFilter(config)
Convert the include exclude filter schema into a filter.
def convert_include_exclude_filter( config: dict[str, dict[str, list[str]]], ) -> EntityFilter: """Convert the include exclude filter schema into a filter.""" include = config[CONF_INCLUDE] exclude = config[CONF_EXCLUDE] return convert_filter( { CONF_INCLUDE_DOMAINS: include[CONF_DOMAINS], CONF_INCLUDE_ENTITY_GLOBS: include[CONF_ENTITY_GLOBS], CONF_INCLUDE_ENTITIES: include[CONF_ENTITIES], CONF_EXCLUDE_DOMAINS: exclude[CONF_DOMAINS], CONF_EXCLUDE_ENTITY_GLOBS: exclude[CONF_ENTITY_GLOBS], CONF_EXCLUDE_ENTITIES: exclude[CONF_ENTITIES], } )
Convert a list of globs to a re pattern list.
def _convert_globs_to_pattern(globs: list[str] | None) -> re.Pattern[str] | None: """Convert a list of globs to a re pattern list.""" if globs is None: return None translated_patterns: list[str] = [ pattern for glob in set(globs) if (pattern := fnmatch.translate(glob)) ] if not translated_patterns: return None inner = "|".join(translated_patterns) combined = f"(?:{inner})" return re.compile(combined)
Return a function that will filter entities based on the args.
def generate_filter( include_domains: list[str], include_entities: list[str], exclude_domains: list[str], exclude_entities: list[str], include_entity_globs: list[str] | None = None, exclude_entity_globs: list[str] | None = None, ) -> Callable[[str], bool]: """Return a function that will filter entities based on the args.""" return _generate_filter_from_sets_and_pattern_lists( set(include_domains), set(include_entities), set(exclude_domains), set(exclude_entities), _convert_globs_to_pattern(include_entity_globs), _convert_globs_to_pattern(exclude_entity_globs), )
Generate a filter from pre-comuted sets and pattern lists.
def _generate_filter_from_sets_and_pattern_lists( include_d: set[str], include_e: set[str], exclude_d: set[str], exclude_e: set[str], include_eg: re.Pattern[str] | None, exclude_eg: re.Pattern[str] | None, ) -> Callable[[str], bool]: """Generate a filter from pre-comuted sets and pattern lists.""" have_exclude = bool(exclude_e or exclude_d or exclude_eg) have_include = bool(include_e or include_d or include_eg) # Case 1 - No filter # - All entities included if not have_include and not have_exclude: return lambda entity_id: True # Case 2 - Only includes # - Entity listed in entities include: include # - Otherwise, entity matches domain include: include # - Otherwise, entity matches glob include: include # - Otherwise: exclude if have_include and not have_exclude: def entity_included(entity_id: str) -> bool: """Return true if entity matches inclusion filters.""" return ( entity_id in include_e or split_entity_id(entity_id)[0] in include_d or (bool(include_eg and include_eg.match(entity_id))) ) # Return filter function for case 2 return entity_included # Case 3 - Only excludes # - Entity listed in exclude: exclude # - Otherwise, entity matches domain exclude: exclude # - Otherwise, entity matches glob exclude: exclude # - Otherwise: include if not have_include and have_exclude: def entity_not_excluded(entity_id: str) -> bool: """Return true if entity matches exclusion filters.""" return not ( entity_id in exclude_e or split_entity_id(entity_id)[0] in exclude_d or (exclude_eg and exclude_eg.match(entity_id)) ) return entity_not_excluded # Case 4 - Domain and/or glob includes (may also have excludes) # - Entity listed in entities include: include # - Otherwise, entity listed in entities exclude: exclude # - Otherwise, entity matches glob include: include # - Otherwise, entity matches glob exclude: exclude # - Otherwise, entity matches domain include: include # - Otherwise: exclude if include_d or include_eg: def entity_filter_4a(entity_id: str) -> bool: """Return filter function for case 4a.""" return entity_id in include_e or ( entity_id not in exclude_e and ( bool(include_eg and include_eg.match(entity_id)) or ( split_entity_id(entity_id)[0] in include_d and not (exclude_eg and exclude_eg.match(entity_id)) ) ) ) return entity_filter_4a # Case 5 - Domain and/or glob excludes (no domain and/or glob includes) # - Entity listed in entities include: include # - Otherwise, entity listed in exclude: exclude # - Otherwise, entity matches glob exclude: exclude # - Otherwise, entity matches domain exclude: exclude # - Otherwise: include if exclude_d or exclude_eg: def entity_filter_4b(entity_id: str) -> bool: """Return filter function for case 4b.""" domain = split_entity_id(entity_id)[0] if domain in exclude_d or bool(exclude_eg and exclude_eg.match(entity_id)): return entity_id in include_e return entity_id not in exclude_e return entity_filter_4b # Case 6 - No Domain and/or glob includes or excludes # - Entity listed in entities include: include # - Otherwise: exclude return lambda entity_id: entity_id in include_e
Get the current platform from context.
def async_get_current_platform() -> EntityPlatform: """Get the current platform from context.""" if (platform := current_platform.get()) is None: raise RuntimeError("Cannot get non-set current platform") return platform
Find existing platforms.
def async_get_platforms( hass: HomeAssistant, integration_name: str ) -> list[EntityPlatform]: """Find existing platforms.""" if ( DATA_ENTITY_PLATFORM not in hass.data or integration_name not in hass.data[DATA_ENTITY_PLATFORM] ): return [] platforms: list[EntityPlatform] = hass.data[DATA_ENTITY_PLATFORM][integration_name] return platforms
Protect entity options from being modified.
def _protect_entity_options( data: EntityOptionsType | None, ) -> ReadOnlyEntityOptionsType: """Protect entity options from being modified.""" if data is None: return ReadOnlyDict({}) return ReadOnlyDict({key: ReadOnlyDict(val) for key, val in data.items()})
Validate entity registry item.
def _validate_item( hass: HomeAssistant, domain: str, platform: str, unique_id: str | Hashable | UndefinedType | Any, *, disabled_by: RegistryEntryDisabler | None | UndefinedType = None, entity_category: EntityCategory | None | UndefinedType = None, hidden_by: RegistryEntryHider | None | UndefinedType = None, ) -> None: """Validate entity registry item.""" if unique_id is not UNDEFINED and not isinstance(unique_id, Hashable): raise TypeError(f"unique_id must be a string, got {unique_id}") if unique_id is not UNDEFINED and not isinstance(unique_id, str): # In HA Core 2025.4, we should fail if unique_id is not a string report_issue = async_suggest_report_issue(hass, integration_domain=platform) _LOGGER.error( ("'%s' from integration %s has a non string unique_id" " '%s', please %s"), domain, platform, unique_id, report_issue, ) if ( disabled_by and disabled_by is not UNDEFINED and not isinstance(disabled_by, RegistryEntryDisabler) ): raise ValueError( f"disabled_by must be a RegistryEntryDisabler value, got {disabled_by}" ) if ( entity_category and entity_category is not UNDEFINED and not isinstance(entity_category, EntityCategory) ): raise ValueError( f"entity_category must be a valid EntityCategory instance, got {entity_category}" ) if ( hidden_by and hidden_by is not UNDEFINED and not isinstance(hidden_by, RegistryEntryHider) ): raise ValueError( f"hidden_by must be a RegistryEntryHider value, got {hidden_by}" )
Get entity registry.
def async_get(hass: HomeAssistant) -> EntityRegistry: """Get entity registry.""" return cast(EntityRegistry, hass.data[DATA_REGISTRY])
Return entries that match a device.
def async_entries_for_device( registry: EntityRegistry, device_id: str, include_disabled_entities: bool = False ) -> list[RegistryEntry]: """Return entries that match a device.""" return registry.entities.get_entries_for_device_id( device_id, include_disabled_entities )