response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Get the floor ID from a floor name.
def floor_id(hass: HomeAssistant, lookup_value: Any) -> str | None: """Get the floor ID from a floor name.""" floor_registry = fr.async_get(hass) if floor := floor_registry.async_get_floor_by_name(str(lookup_value)): return floor.floor_id if aid := area_id(hass, lookup_value): area_reg = area_registry.async_get(hass) if area := area_reg.async_get_area(aid): return area.floor_id return None
Get the floor name from a floor id.
def floor_name(hass: HomeAssistant, lookup_value: str) -> str | None: """Get the floor name from a floor id.""" floor_registry = fr.async_get(hass) if floor := floor_registry.async_get_floor(lookup_value): return floor.name if aid := area_id(hass, lookup_value): area_reg = area_registry.async_get(hass) if ( (area := area_reg.async_get_area(aid)) and area.floor_id and (floor := floor_registry.async_get_floor(area.floor_id)) ): return floor.name return None
Return area IDs for a given floor ID or name.
def floor_areas(hass: HomeAssistant, floor_id_or_name: str) -> Iterable[str]: """Return area IDs for a given floor ID or name.""" _floor_id: str | None # If floor_name returns a value, we know the input was an ID, otherwise we # assume it's a name, and if it's neither, we return early if floor_name(hass, floor_id_or_name) is not None: _floor_id = floor_id_or_name else: _floor_id = floor_id(hass, floor_id_or_name) if _floor_id is None: return [] area_reg = area_registry.async_get(hass) entries = area_registry.async_entries_for_floor(area_reg, _floor_id) return [entry.id for entry in entries if entry.id]
Return all areas.
def areas(hass: HomeAssistant) -> Iterable[str | None]: """Return all areas.""" return list(area_registry.async_get(hass).areas)
Get the area ID from an area name, device id, or entity id.
def area_id(hass: HomeAssistant, lookup_value: str) -> str | None: """Get the area ID from an area name, device id, or entity id.""" area_reg = area_registry.async_get(hass) if area := area_reg.async_get_area_by_name(str(lookup_value)): return area.id ent_reg = entity_registry.async_get(hass) dev_reg = device_registry.async_get(hass) # Import here, not at top-level to avoid circular import from . import config_validation as cv # pylint: disable=import-outside-toplevel try: cv.entity_id(lookup_value) except vol.Invalid: pass else: if entity := ent_reg.async_get(lookup_value): # If entity has an area ID, return that if entity.area_id: return entity.area_id # If entity has a device ID, return the area ID for the device if entity.device_id and (device := dev_reg.async_get(entity.device_id)): return device.area_id # Check if this could be a device ID if device := dev_reg.async_get(lookup_value): return device.area_id return None
Get area name from valid area ID.
def _get_area_name(area_reg: area_registry.AreaRegistry, valid_area_id: str) -> str: """Get area name from valid area ID.""" area = area_reg.async_get_area(valid_area_id) assert area return area.name
Get the area name from an area id, device id, or entity id.
def area_name(hass: HomeAssistant, lookup_value: str) -> str | None: """Get the area name from an area id, device id, or entity id.""" area_reg = area_registry.async_get(hass) if area := area_reg.async_get_area(lookup_value): return area.name dev_reg = device_registry.async_get(hass) ent_reg = entity_registry.async_get(hass) # Import here, not at top-level to avoid circular import from . import config_validation as cv # pylint: disable=import-outside-toplevel try: cv.entity_id(lookup_value) except vol.Invalid: pass else: if entity := ent_reg.async_get(lookup_value): # If entity has an area ID, get the area name for that if entity.area_id: return _get_area_name(area_reg, entity.area_id) # If entity has a device ID and the device exists with an area ID, get the # area name for that if ( entity.device_id and (device := dev_reg.async_get(entity.device_id)) and device.area_id ): return _get_area_name(area_reg, device.area_id) if (device := dev_reg.async_get(lookup_value)) and device.area_id: return _get_area_name(area_reg, device.area_id) return None
Return entities for a given area ID or name.
def area_entities(hass: HomeAssistant, area_id_or_name: str) -> Iterable[str]: """Return entities for a given area ID or name.""" _area_id: str | None # if area_name returns a value, we know the input was an ID, otherwise we # assume it's a name, and if it's neither, we return early if area_name(hass, area_id_or_name) is None: _area_id = area_id(hass, area_id_or_name) else: _area_id = area_id_or_name if _area_id is None: return [] ent_reg = entity_registry.async_get(hass) entity_ids = [ entry.entity_id for entry in entity_registry.async_entries_for_area(ent_reg, _area_id) ] dev_reg = device_registry.async_get(hass) # We also need to add entities tied to a device in the area that don't themselves # have an area specified since they inherit the area from the device. entity_ids.extend( [ entity.entity_id for device in device_registry.async_entries_for_area(dev_reg, _area_id) for entity in entity_registry.async_entries_for_device(ent_reg, device.id) if entity.area_id is None ] ) return entity_ids
Return device IDs for a given area ID or name.
def area_devices(hass: HomeAssistant, area_id_or_name: str) -> Iterable[str]: """Return device IDs for a given area ID or name.""" _area_id: str | None # if area_name returns a value, we know the input was an ID, otherwise we # assume it's a name, and if it's neither, we return early if area_name(hass, area_id_or_name) is not None: _area_id = area_id_or_name else: _area_id = area_id(hass, area_id_or_name) if _area_id is None: return [] dev_reg = device_registry.async_get(hass) entries = device_registry.async_entries_for_area(dev_reg, _area_id) return [entry.id for entry in entries]
Return all labels, or those from a area ID, device ID, or entity ID.
def labels(hass: HomeAssistant, lookup_value: Any = None) -> Iterable[str | None]: """Return all labels, or those from a area ID, device ID, or entity ID.""" label_reg = label_registry.async_get(hass) if lookup_value is None: return list(label_reg.labels) ent_reg = entity_registry.async_get(hass) # Import here, not at top-level to avoid circular import from . import config_validation as cv # pylint: disable=import-outside-toplevel lookup_value = str(lookup_value) try: cv.entity_id(lookup_value) except vol.Invalid: pass else: if entity := ent_reg.async_get(lookup_value): return list(entity.labels) # Check if this could be a device ID dev_reg = device_registry.async_get(hass) if device := dev_reg.async_get(lookup_value): return list(device.labels) # Check if this could be a area ID area_reg = area_registry.async_get(hass) if area := area_reg.async_get_area(lookup_value): return list(area.labels) return []
Get the label ID from a label name.
def label_id(hass: HomeAssistant, lookup_value: Any) -> str | None: """Get the label ID from a label name.""" label_reg = label_registry.async_get(hass) if label := label_reg.async_get_label_by_name(str(lookup_value)): return label.label_id return None
Get the label name from a label ID.
def label_name(hass: HomeAssistant, lookup_value: str) -> str | None: """Get the label name from a label ID.""" label_reg = label_registry.async_get(hass) if label := label_reg.async_get_label(lookup_value): return label.name return None
Get the label ID from a label name or ID.
def _label_id_or_name(hass: HomeAssistant, label_id_or_name: str) -> str | None: """Get the label ID from a label name or ID.""" # If label_name returns a value, we know the input was an ID, otherwise we # assume it's a name, and if it's neither, we return early. if label_name(hass, label_id_or_name) is not None: return label_id_or_name return label_id(hass, label_id_or_name)
Return areas for a given label ID or name.
def label_areas(hass: HomeAssistant, label_id_or_name: str) -> Iterable[str]: """Return areas for a given label ID or name.""" if (_label_id := _label_id_or_name(hass, label_id_or_name)) is None: return [] area_reg = area_registry.async_get(hass) entries = area_registry.async_entries_for_label(area_reg, _label_id) return [entry.id for entry in entries]
Return device IDs for a given label ID or name.
def label_devices(hass: HomeAssistant, label_id_or_name: str) -> Iterable[str]: """Return device IDs for a given label ID or name.""" if (_label_id := _label_id_or_name(hass, label_id_or_name)) is None: return [] dev_reg = device_registry.async_get(hass) entries = device_registry.async_entries_for_label(dev_reg, _label_id) return [entry.id for entry in entries]
Return entities for a given label ID or name.
def label_entities(hass: HomeAssistant, label_id_or_name: str) -> Iterable[str]: """Return entities for a given label ID or name.""" if (_label_id := _label_id_or_name(hass, label_id_or_name)) is None: return [] ent_reg = entity_registry.async_get(hass) entries = entity_registry.async_entries_for_label(ent_reg, _label_id) return [entry.entity_id for entry in entries]
Find closest entity. Closest to home: closest(states) closest(states.device_tracker) closest('group.children') closest(states.group.children) Closest to a point: closest(23.456, 23.456, 'group.children') closest('zone.school', 'group.children') closest(states.zone.school, 'group.children') As a filter: states | closest states.device_tracker | closest ['group.children', states.device_tracker] | closest 'group.children' | closest(23.456, 23.456) states.device_tracker | closest('zone.school') 'group.children' | closest(states.zone.school)
def closest(hass, *args): """Find closest entity. Closest to home: closest(states) closest(states.device_tracker) closest('group.children') closest(states.group.children) Closest to a point: closest(23.456, 23.456, 'group.children') closest('zone.school', 'group.children') closest(states.zone.school, 'group.children') As a filter: states | closest states.device_tracker | closest ['group.children', states.device_tracker] | closest 'group.children' | closest(23.456, 23.456) states.device_tracker | closest('zone.school') 'group.children' | closest(states.zone.school) """ if len(args) == 1: latitude = hass.config.latitude longitude = hass.config.longitude entities = args[0] elif len(args) == 2: point_state = _resolve_state(hass, args[0]) if point_state is None: _LOGGER.warning("Closest:Unable to find state %s", args[0]) return None if not loc_helper.has_location(point_state): _LOGGER.warning( "Closest:State does not contain valid location: %s", point_state ) return None latitude = point_state.attributes.get(ATTR_LATITUDE) longitude = point_state.attributes.get(ATTR_LONGITUDE) entities = args[1] else: latitude = convert(args[0], float) longitude = convert(args[1], float) if latitude is None or longitude is None: _LOGGER.warning( "Closest:Received invalid coordinates: %s, %s", args[0], args[1] ) return None entities = args[2] states = expand(hass, entities) # state will already be wrapped here return loc_helper.closest(latitude, longitude, states)
Call closest as a filter. Need to reorder arguments.
def closest_filter(hass, *args): """Call closest as a filter. Need to reorder arguments.""" new_args = list(args[1:]) new_args.append(args[0]) return closest(hass, *new_args)
Calculate distance. Will calculate distance from home to a point or between points. Points can be passed in using state objects or lat/lng coordinates.
def distance(hass, *args): """Calculate distance. Will calculate distance from home to a point or between points. Points can be passed in using state objects or lat/lng coordinates. """ locations = [] to_process = list(args) while to_process: value = to_process.pop(0) if isinstance(value, str) and not valid_entity_id(value): point_state = None else: point_state = _resolve_state(hass, value) if point_state is None: # We expect this and next value to be lat&lng if not to_process: _LOGGER.warning( "Distance:Expected latitude and longitude, got %s", value ) return None value_2 = to_process.pop(0) latitude = convert(value, float) longitude = convert(value_2, float) if latitude is None or longitude is None: _LOGGER.warning( "Distance:Unable to process latitude and longitude: %s, %s", value, value_2, ) return None else: if not loc_helper.has_location(point_state): _LOGGER.warning( "Distance:State does not contain valid location: %s", point_state ) return None latitude = point_state.attributes.get(ATTR_LATITUDE) longitude = point_state.attributes.get(ATTR_LONGITUDE) locations.append((latitude, longitude)) if len(locations) == 1: return hass.config.distance(*locations[0]) return hass.config.units.length( loc_util.distance(*locations[0] + locations[1]), UnitOfLength.METERS )
Test if an entity is hidden.
def is_hidden_entity(hass: HomeAssistant, entity_id: str) -> bool: """Test if an entity is hidden.""" entity_reg = entity_registry.async_get(hass) entry = entity_reg.async_get(entity_id) return entry is not None and entry.hidden
Test if a state is a specific value.
def is_state(hass: HomeAssistant, entity_id: str, state: str | list[str]) -> bool: """Test if a state is a specific value.""" state_obj = _get_state(hass, entity_id) return state_obj is not None and ( state_obj.state == state or isinstance(state, list) and state_obj.state in state )
Test if a state's attribute is a specific value.
def is_state_attr(hass: HomeAssistant, entity_id: str, name: str, value: Any) -> bool: """Test if a state's attribute is a specific value.""" attr = state_attr(hass, entity_id, name) return attr is not None and attr == value
Get a specific attribute from a state.
def state_attr(hass: HomeAssistant, entity_id: str, name: str) -> Any: """Get a specific attribute from a state.""" if (state_obj := _get_state(hass, entity_id)) is not None: return state_obj.attributes.get(name) return None
Test if an entity has a valid value.
def has_value(hass: HomeAssistant, entity_id: str) -> bool: """Test if an entity has a valid value.""" state_obj = _get_state(hass, entity_id) return state_obj is not None and ( state_obj.state not in [STATE_UNAVAILABLE, STATE_UNKNOWN] )
Record fetching now.
def now(hass: HomeAssistant) -> datetime: """Record fetching now.""" if (render_info := _render_info.get()) is not None: render_info.has_time = True return dt_util.now()
Record fetching utcnow.
def utcnow(hass: HomeAssistant) -> datetime: """Record fetching utcnow.""" if (render_info := _render_info.get()) is not None: render_info.has_time = True return dt_util.utcnow()
Log warning if no default is specified.
def raise_no_default(function: str, value: Any) -> NoReturn: """Log warning if no default is specified.""" template, action = template_cv.get() or ("", "rendering or compiling") raise ValueError( f"Template error: {function} got invalid input '{value}' when {action} template" f" '{template}' but no default was specified" )
Filter to round a value.
def forgiving_round(value, precision=0, method="common", default=_SENTINEL): """Filter to round a value.""" try: # support rounding methods like jinja multiplier = float(10**precision) if method == "ceil": value = math.ceil(float(value) * multiplier) / multiplier elif method == "floor": value = math.floor(float(value) * multiplier) / multiplier elif method == "half": value = round(float(value) * 2) / 2 else: # if method is common or something else, use common rounding value = round(float(value), precision) return int(value) if precision == 0 else value except (ValueError, TypeError): # If value can't be converted to float if default is _SENTINEL: raise_no_default("round", value) return default
Filter to convert value to float and multiply it.
def multiply(value, amount, default=_SENTINEL): """Filter to convert value to float and multiply it.""" try: return float(value) * amount except (ValueError, TypeError): # If value can't be converted to float if default is _SENTINEL: raise_no_default("multiply", value) return default
Filter and function to get logarithm of the value with a specific base.
def logarithm(value, base=math.e, default=_SENTINEL): """Filter and function to get logarithm of the value with a specific base.""" try: base_float = float(base) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("log", base) return default try: value_float = float(value) return math.log(value_float, base_float) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("log", value) return default
Filter and function to get sine of the value.
def sine(value, default=_SENTINEL): """Filter and function to get sine of the value.""" try: return math.sin(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("sin", value) return default
Filter and function to get cosine of the value.
def cosine(value, default=_SENTINEL): """Filter and function to get cosine of the value.""" try: return math.cos(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("cos", value) return default
Filter and function to get tangent of the value.
def tangent(value, default=_SENTINEL): """Filter and function to get tangent of the value.""" try: return math.tan(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("tan", value) return default
Filter and function to get arc sine of the value.
def arc_sine(value, default=_SENTINEL): """Filter and function to get arc sine of the value.""" try: return math.asin(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("asin", value) return default
Filter and function to get arc cosine of the value.
def arc_cosine(value, default=_SENTINEL): """Filter and function to get arc cosine of the value.""" try: return math.acos(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("acos", value) return default
Filter and function to get arc tangent of the value.
def arc_tangent(value, default=_SENTINEL): """Filter and function to get arc tangent of the value.""" try: return math.atan(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("atan", value) return default
Filter and function to calculate four quadrant arc tangent of y / x. The parameters to atan2 may be passed either in an iterable or as separate arguments The default value may be passed either as a positional or in a keyword argument
def arc_tangent2(*args, default=_SENTINEL): """Filter and function to calculate four quadrant arc tangent of y / x. The parameters to atan2 may be passed either in an iterable or as separate arguments The default value may be passed either as a positional or in a keyword argument """ try: if 1 <= len(args) <= 2 and isinstance(args[0], (list, tuple)): if len(args) == 2 and default is _SENTINEL: # Default value passed as a positional argument default = args[1] args = args[0] elif len(args) == 3 and default is _SENTINEL: # Default value passed as a positional argument default = args[2] return math.atan2(float(args[0]), float(args[1])) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("atan2", args) return default
Filter and function to get version object of the value.
def version(value): """Filter and function to get version object of the value.""" return AwesomeVersion(value)
Filter and function to get square root of the value.
def square_root(value, default=_SENTINEL): """Filter and function to get square root of the value.""" try: return math.sqrt(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("sqrt", value) return default
Filter to convert given timestamp to format.
def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True, default=_SENTINEL): """Filter to convert given timestamp to format.""" try: result = dt_util.utc_from_timestamp(value) if local: result = dt_util.as_local(result) return result.strftime(date_format) except (ValueError, TypeError): # If timestamp can't be converted if default is _SENTINEL: raise_no_default("timestamp_custom", value) return default
Filter to convert given timestamp to local date/time.
def timestamp_local(value, default=_SENTINEL): """Filter to convert given timestamp to local date/time.""" try: return dt_util.as_local(dt_util.utc_from_timestamp(value)).isoformat() except (ValueError, TypeError): # If timestamp can't be converted if default is _SENTINEL: raise_no_default("timestamp_local", value) return default
Filter to convert given timestamp to UTC date/time.
def timestamp_utc(value, default=_SENTINEL): """Filter to convert given timestamp to UTC date/time.""" try: return dt_util.utc_from_timestamp(value).isoformat() except (ValueError, TypeError): # If timestamp can't be converted if default is _SENTINEL: raise_no_default("timestamp_utc", value) return default
Filter and function which tries to convert value to timestamp.
def forgiving_as_timestamp(value, default=_SENTINEL): """Filter and function which tries to convert value to timestamp.""" try: return dt_util.as_timestamp(value) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("as_timestamp", value) return default
Filter and to convert a time string or UNIX timestamp to datetime object.
def as_datetime(value: Any, default: Any = _SENTINEL) -> Any: """Filter and to convert a time string or UNIX timestamp to datetime object.""" # Return datetime.datetime object without changes if type(value) is datetime: return value # Add midnight to datetime.date object if type(value) is date: return datetime.combine(value, time(0, 0, 0)) try: # Check for a valid UNIX timestamp string, int or float timestamp = float(value) return dt_util.utc_from_timestamp(timestamp) except (ValueError, TypeError): # Try to parse datetime string to datetime object try: return dt_util.parse_datetime(value, raise_on_error=True) except (ValueError, TypeError): if default is _SENTINEL: # Return None on string input # to ensure backwards compatibility with HA Core 2024.1 and before. if isinstance(value, str): return None raise_no_default("as_datetime", value) return default
Parse a ISO8601 duration like 'PT10M' to a timedelta.
def as_timedelta(value: str) -> timedelta | None: """Parse a ISO8601 duration like 'PT10M' to a timedelta.""" return dt_util.parse_duration(value)
Parse a time string to datetime.
def strptime(string, fmt, default=_SENTINEL): """Parse a time string to datetime.""" try: return datetime.strptime(string, fmt) except (ValueError, AttributeError, TypeError): if default is _SENTINEL: raise_no_default("strptime", string) return default
Filter to force a failure when the value is undefined.
def fail_when_undefined(value): """Filter to force a failure when the value is undefined.""" if isinstance(value, jinja2.Undefined): value() return value
Convert a built-in min/max Jinja filter to a global function. The parameters may be passed as an iterable or as separate arguments.
def min_max_from_filter(builtin_filter: Any, name: str) -> Any: """Convert a built-in min/max Jinja filter to a global function. The parameters may be passed as an iterable or as separate arguments. """ @pass_environment @wraps(builtin_filter) def wrapper(environment: jinja2.Environment, *args: Any, **kwargs: Any) -> Any: if len(args) == 0: raise TypeError(f"{name} expected at least 1 argument, got 0") if len(args) == 1: if isinstance(args[0], Iterable): return builtin_filter(environment, args[0], **kwargs) raise TypeError(f"'{type(args[0]).__name__}' object is not iterable") return builtin_filter(environment, args, **kwargs) return pass_environment(wrapper)
Filter and function to calculate the arithmetic mean. Calculates of an iterable or of two or more arguments. The parameters may be passed as an iterable or as separate arguments.
def average(*args: Any, default: Any = _SENTINEL) -> Any: """Filter and function to calculate the arithmetic mean. Calculates of an iterable or of two or more arguments. The parameters may be passed as an iterable or as separate arguments. """ if len(args) == 0: raise TypeError("average expected at least 1 argument, got 0") # If first argument is iterable and more than 1 argument provided but not a named # default, then use 2nd argument as default. if isinstance(args[0], Iterable): average_list = args[0] if len(args) > 1 and default is _SENTINEL: default = args[1] elif len(args) == 1: raise TypeError(f"'{type(args[0]).__name__}' object is not iterable") else: average_list = args try: return statistics.fmean(average_list) except (TypeError, statistics.StatisticsError): if default is _SENTINEL: raise_no_default("average", args) return default
Filter and function to calculate the median. Calculates median of an iterable of two or more arguments. The parameters may be passed as an iterable or as separate arguments.
def median(*args: Any, default: Any = _SENTINEL) -> Any: """Filter and function to calculate the median. Calculates median of an iterable of two or more arguments. The parameters may be passed as an iterable or as separate arguments. """ if len(args) == 0: raise TypeError("median expected at least 1 argument, got 0") # If first argument is a list or tuple and more than 1 argument provided but not a named # default, then use 2nd argument as default. if isinstance(args[0], Iterable): median_list = args[0] if len(args) > 1 and default is _SENTINEL: default = args[1] elif len(args) == 1: raise TypeError(f"'{type(args[0]).__name__}' object is not iterable") else: median_list = args try: return statistics.median(median_list) except (TypeError, statistics.StatisticsError): if default is _SENTINEL: raise_no_default("median", args) return default
Filter and function to calculate the statistical mode. Calculates mode of an iterable of two or more arguments. The parameters may be passed as an iterable or as separate arguments.
def statistical_mode(*args: Any, default: Any = _SENTINEL) -> Any: """Filter and function to calculate the statistical mode. Calculates mode of an iterable of two or more arguments. The parameters may be passed as an iterable or as separate arguments. """ if not args: raise TypeError("statistical_mode expected at least 1 argument, got 0") # If first argument is a list or tuple and more than 1 argument provided but not a named # default, then use 2nd argument as default. if len(args) == 1 and isinstance(args[0], Iterable): mode_list = args[0] elif isinstance(args[0], list | tuple): mode_list = args[0] if len(args) > 1 and default is _SENTINEL: default = args[1] elif len(args) == 1: raise TypeError(f"'{type(args[0]).__name__}' object is not iterable") else: mode_list = args try: return statistics.mode(mode_list) except (TypeError, statistics.StatisticsError): if default is _SENTINEL: raise_no_default("statistical_mode", args) return default
Try to convert value to a float.
def forgiving_float(value, default=_SENTINEL): """Try to convert value to a float.""" try: return float(value) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("float", value) return default
Try to convert value to a float.
def forgiving_float_filter(value, default=_SENTINEL): """Try to convert value to a float.""" try: return float(value) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("float", value) return default
Try to convert value to an int, and raise if it fails.
def forgiving_int(value, default=_SENTINEL, base=10): """Try to convert value to an int, and raise if it fails.""" result = jinja2.filters.do_int(value, default=default, base=base) if result is _SENTINEL: raise_no_default("int", value) return result
Try to convert value to an int, and raise if it fails.
def forgiving_int_filter(value, default=_SENTINEL, base=10): """Try to convert value to an int, and raise if it fails.""" result = jinja2.filters.do_int(value, default=default, base=base) if result is _SENTINEL: raise_no_default("int", value) return result
Try to convert value to a float.
def is_number(value): """Try to convert value to a float.""" try: fvalue = float(value) except (ValueError, TypeError): return False if not math.isfinite(fvalue): return False return True
Return whether a value is a list.
def _is_list(value: Any) -> bool: """Return whether a value is a list.""" return isinstance(value, list)
Return whether a value is a set.
def _is_set(value: Any) -> bool: """Return whether a value is a set.""" return isinstance(value, set)
Return whether a value is a tuple.
def _is_tuple(value: Any) -> bool: """Return whether a value is a tuple.""" return isinstance(value, tuple)
Convert value to set.
def _to_set(value: Any) -> set[Any]: """Convert value to set.""" return set(value)
Convert value to tuple.
def _to_tuple(value): """Convert value to tuple.""" return tuple(value)
Return whether a value is a datetime.
def _is_datetime(value: Any) -> bool: """Return whether a value is a datetime.""" return isinstance(value, datetime)
Return whether a value is a string or string like object.
def _is_string_like(value: Any) -> bool: """Return whether a value is a string or string like object.""" return isinstance(value, (str, bytes, bytearray))
Match value using regex.
def regex_match(value, find="", ignorecase=False): """Match value using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return bool(_regex_cache(find, flags).match(value))
Replace using regex.
def regex_replace(value="", find="", replace="", ignorecase=False): """Replace using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return _regex_cache(find, flags).sub(replace, value)
Search using regex.
def regex_search(value, find="", ignorecase=False): """Search using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return bool(_regex_cache(find, flags).search(value))
Find all matches using regex and then pick specific match index.
def regex_findall_index(value, find="", index=0, ignorecase=False): """Find all matches using regex and then pick specific match index.""" return regex_findall(value, find, ignorecase)[index]
Find all matches using regex.
def regex_findall(value, find="", ignorecase=False): """Find all matches using regex.""" if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 return _regex_cache(find, flags).findall(value)
Perform a bitwise and operation.
def bitwise_and(first_value, second_value): """Perform a bitwise and operation.""" return first_value & second_value
Perform a bitwise or operation.
def bitwise_or(first_value, second_value): """Perform a bitwise or operation.""" return first_value | second_value
Perform a bitwise xor operation.
def bitwise_xor(first_value, second_value): """Perform a bitwise xor operation.""" return first_value ^ second_value
Pack an object into a bytes object.
def struct_pack(value: Any | None, format_string: str) -> bytes | None: """Pack an object into a bytes object.""" try: return pack(format_string, value) except StructError: _LOGGER.warning( ( "Template warning: 'pack' unable to pack object '%s' with type '%s' and" " format_string '%s' see https://docs.python.org/3/library/struct.html" " for more information" ), str(value), type(value).__name__, format_string, ) return None
Unpack an object from bytes an return the first native object.
def struct_unpack(value: bytes, format_string: str, offset: int = 0) -> Any | None: """Unpack an object from bytes an return the first native object.""" try: return unpack_from(format_string, value, offset)[0] except StructError: _LOGGER.warning( ( "Template warning: 'unpack' unable to unpack object '%s' with" " format_string '%s' and offset %s see" " https://docs.python.org/3/library/struct.html for more information" ), value, format_string, offset, ) return None
Perform base64 encode.
def base64_encode(value): """Perform base64 encode.""" return base64.b64encode(value.encode("utf-8")).decode("utf-8")
Perform base64 denode.
def base64_decode(value): """Perform base64 denode.""" return base64.b64decode(value).decode("utf-8")
Perform ordinal conversion.
def ordinal(value): """Perform ordinal conversion.""" return str(value) + ( list(["th", "st", "nd", "rd"] + ["th"] * 6)[(int(str(value)[-1])) % 10] if int(str(value)[-2:]) % 100 not in range(11, 14) else "th" )
Convert a JSON string to an object.
def from_json(value): """Convert a JSON string to an object.""" return json_loads(value)
Disable custom types in json serialization.
def _to_json_default(obj: Any) -> None: """Disable custom types in json serialization.""" raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
Convert an object to a JSON string.
def to_json( value: Any, ensure_ascii: bool = False, pretty_print: bool = False, sort_keys: bool = False, ) -> str: """Convert an object to a JSON string.""" if ensure_ascii: # For those who need ascii, we can't use orjson, so we fall back to the json library. return json.dumps( value, ensure_ascii=ensure_ascii, indent=2 if pretty_print else None, sort_keys=sort_keys, ) option = ( ORJSON_PASSTHROUGH_OPTIONS # OPT_NON_STR_KEYS is added as a workaround to # ensure subclasses of str are allowed as dict keys # See: https://github.com/ijl/orjson/issues/445 | orjson.OPT_NON_STR_KEYS | (orjson.OPT_INDENT_2 if pretty_print else 0) | (orjson.OPT_SORT_KEYS if sort_keys else 0) ) return orjson.dumps( value, option=option, default=_to_json_default, ).decode("utf-8")
Choose a random value. Unlike Jinja's random filter, this is context-dependent to avoid caching the chosen value.
def random_every_time(context, values): """Choose a random value. Unlike Jinja's random filter, this is context-dependent to avoid caching the chosen value. """ return random.choice(values)
Record fetching now where the time has been replaced with value.
def today_at(hass: HomeAssistant, time_str: str = "") -> datetime: """Record fetching now where the time has been replaced with value.""" if (render_info := _render_info.get()) is not None: render_info.has_time = True today = dt_util.start_of_local_day() if not time_str: return today if (time_today := dt_util.parse_time(time_str)) is None: raise ValueError( f"could not convert {type(time_str).__name__} to datetime: '{time_str}'" ) return datetime.combine(today, time_today, today.tzinfo)
Take a datetime and return its "age" as a string. The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will be returned. If the input datetime is in the future, the input datetime will be returned. If the input are not a datetime object the input will be returned unmodified. Note: This template function is deprecated in favor of `time_until`, but is still supported so as not to break old templates.
def relative_time(hass: HomeAssistant, value: Any) -> Any: """Take a datetime and return its "age" as a string. The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will be returned. If the input datetime is in the future, the input datetime will be returned. If the input are not a datetime object the input will be returned unmodified. Note: This template function is deprecated in favor of `time_until`, but is still supported so as not to break old templates. """ if (render_info := _render_info.get()) is not None: render_info.has_time = True if not isinstance(value, datetime): return value if not value.tzinfo: value = dt_util.as_local(value) if dt_util.now() < value: return value return dt_util.get_age(value)
Take a datetime and return its "age" as a string. The age can be in seconds, minutes, hours, days, months and year. precision is the number of units to return, with the last unit rounded. If the value not a datetime object the input will be returned unmodified.
def time_since(hass: HomeAssistant, value: Any | datetime, precision: int = 1) -> Any: """Take a datetime and return its "age" as a string. The age can be in seconds, minutes, hours, days, months and year. precision is the number of units to return, with the last unit rounded. If the value not a datetime object the input will be returned unmodified. """ if (render_info := _render_info.get()) is not None: render_info.has_time = True if not isinstance(value, datetime): return value if not value.tzinfo: value = dt_util.as_local(value) if dt_util.now() < value: return value return dt_util.get_age(value, precision)
Take a datetime and return the amount of time until that time as a string. The time until can be in seconds, minutes, hours, days, months and years. precision is the number of units to return, with the last unit rounded. If the value not a datetime object the input will be returned unmodified.
def time_until(hass: HomeAssistant, value: Any | datetime, precision: int = 1) -> Any: """Take a datetime and return the amount of time until that time as a string. The time until can be in seconds, minutes, hours, days, months and years. precision is the number of units to return, with the last unit rounded. If the value not a datetime object the input will be returned unmodified. """ if (render_info := _render_info.get()) is not None: render_info.has_time = True if not isinstance(value, datetime): return value if not value.tzinfo: value = dt_util.as_local(value) if dt_util.now() > value: return value return dt_util.get_time_remaining(value, precision)
Urlencode dictionary and return as UTF-8 string.
def urlencode(value): """Urlencode dictionary and return as UTF-8 string.""" return urllib_urlencode(value).encode("utf-8")
Convert a string into a slug, such as what is used for entity ids.
def slugify(value, separator="_"): """Convert a string into a slug, such as what is used for entity ids.""" return slugify_util(value, separator=separator)
Immediate if function/filter that allow for common if/else constructs. https://en.wikipedia.org/wiki/IIf Examples: {{ is_state("device_tracker.frenck", "home") | iif("yes", "no") }} {{ iif(1==2, "yes", "no") }} {{ (1 == 1) | iif("yes", "no") }}
def iif( value: Any, if_true: Any = True, if_false: Any = False, if_none: Any = _SENTINEL ) -> Any: """Immediate if function/filter that allow for common if/else constructs. https://en.wikipedia.org/wiki/IIf Examples: {{ is_state("device_tracker.frenck", "home") | iif("yes", "no") }} {{ iif(1==2, "yes", "no") }} {{ (1 == 1) | iif("yes", "no") }} """ if value is None and if_none is not _SENTINEL: return if_none if bool(value): return if_true return if_false
Store template being rendered in a ContextVar to aid error handling.
def _render_with_context( template_str: str, template: jinja2.Template, **kwargs: Any ) -> str: """Store template being rendered in a ContextVar to aid error handling.""" with _template_context_manager as cm: cm.set_template(template_str, "rendering") return template.render(**kwargs)
Log on undefined variables.
def make_logging_undefined( strict: bool | None, log_fn: Callable[[int, str], None] | None ) -> type[jinja2.Undefined]: """Log on undefined variables.""" if strict: return jinja2.StrictUndefined def _log_with_logger(level: int, msg: str) -> None: template, action = template_cv.get() or ("", "rendering or compiling") _LOGGER.log( level, "Template variable %s: %s when %s '%s'", logging.getLevelName(level).lower(), msg, action, template, ) _log_fn = log_fn or _log_with_logger class LoggingUndefined(jinja2.Undefined): """Log on undefined variables.""" def _log_message(self) -> None: _log_fn(logging.WARNING, self._undefined_message) def _fail_with_undefined_error(self, *args, **kwargs): try: return super()._fail_with_undefined_error(*args, **kwargs) except self._undefined_exception: _log_fn(logging.ERROR, self._undefined_message) raise def __str__(self) -> str: """Log undefined __str___.""" self._log_message() return super().__str__() def __iter__(self): """Log undefined __iter___.""" self._log_message() return super().__iter__() def __bool__(self) -> bool: """Log undefined __bool___.""" self._log_message() return super().__bool__() return LoggingUndefined
Set id of the current trace.
def trace_id_set(trace_id: tuple[str, str]) -> None: """Set id of the current trace.""" trace_id_cv.set(trace_id)
Get id if the current trace.
def trace_id_get() -> tuple[str, str] | None: """Get id if the current trace.""" return trace_id_cv.get()
Push an element to the top of a trace stack.
def trace_stack_push(trace_stack_var: ContextVar[list[_T] | None], node: _T) -> None: """Push an element to the top of a trace stack.""" trace_stack: list[_T] | None if (trace_stack := trace_stack_var.get()) is None: trace_stack = [] trace_stack_var.set(trace_stack) trace_stack.append(node)
Remove the top element from a trace stack.
def trace_stack_pop(trace_stack_var: ContextVar[list[Any] | None]) -> None: """Remove the top element from a trace stack.""" trace_stack = trace_stack_var.get() if trace_stack is not None: trace_stack.pop()
Return the element at the top of a trace stack.
def trace_stack_top(trace_stack_var: ContextVar[list[_T] | None]) -> _T | None: """Return the element at the top of a trace stack.""" trace_stack = trace_stack_var.get() return trace_stack[-1] if trace_stack else None
Go deeper in the config tree.
def trace_path_push(suffix: str | list[str]) -> int: """Go deeper in the config tree.""" if isinstance(suffix, str): suffix = [suffix] for node in suffix: trace_stack_push(trace_path_stack_cv, node) return len(suffix)
Go n levels up in the config tree.
def trace_path_pop(count: int) -> None: """Go n levels up in the config tree.""" for _ in range(count): trace_stack_pop(trace_path_stack_cv)
Return a string representing the current location in the config tree.
def trace_path_get() -> str: """Return a string representing the current location in the config tree.""" if not (path := trace_path_stack_cv.get()): return "" return "/".join(path)
Append a TraceElement to trace[path].
def trace_append_element( trace_element: TraceElement, maxlen: int | None = None, ) -> None: """Append a TraceElement to trace[path].""" if (trace := trace_cv.get()) is None: trace = {} trace_cv.set(trace) if (path := trace_element.path) not in trace: trace[path] = deque(maxlen=maxlen) trace[path].append(trace_element)
Return the current trace.
def trace_get(clear: bool = True) -> dict[str, deque[TraceElement]] | None: """Return the current trace.""" if clear: trace_clear() return trace_cv.get()
Clear the trace.
def trace_clear() -> None: """Clear the trace.""" trace_cv.set({}) trace_stack_cv.set(None) trace_path_stack_cv.set(None) variables_cv.set(None) script_execution_cv.set(StopReason())