Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bool template filter and function #74068

Merged
merged 3 commits into from Jun 28, 2022
Merged

Conversation

pyos
Copy link
Contributor

@pyos pyos commented Jun 27, 2022

Proposed change

Add a new template filter (and a matching function) bool, analogous to the existing float, int, as_timestamp, etc. The filter returns true for "true", "yes", "on", "enable", "1", boolean true, and non-zero numbers; and false for "false", "no", "off", "disable", "0", boolean false, and zero. In other cases an error is thrown or a default is returned, if specified.

The motivation for this are binary sensors and similar entities. If they were only on or off, an is_state(..., "on") would be sufficient; however, they could also be unknown or unavailable, and handling that currently requires long if-else chains. For numeric sensors we can do states("sensor.temperature") | int(none) to get either the value or none, and this PR makes something like states("binary_sensor.door") | bool(none) possible as well. This synergizes with the existing iif filter: states("binary_sensor.door") | bool(none) | iif("open", "closed", "sensor died").

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Black (black --fast homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

To help with the load of incoming pull requests:

Similar to float and int, but converts to either true or false.

"on", "true", "yes", "enable", true, and non-0 numbers are considered
true; "off", "false", "no", "disable", false, and 0 are false; other
values either throw or produce a default.
@emontnemery emontnemery added the noteworthy Marks a PR as noteworthy and should be in the release notes (in case it normally would not appear) label Jun 28, 2022
Copy link
Contributor

@emontnemery emontnemery left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestions for fixing the typing.

These changes are also needed:

diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py
index 55bde9bbb5..5fce146e3b 100644
--- a/homeassistant/helpers/template.py
+++ b/homeassistant/helpers/template.py
@@ -19,7 +19,7 @@ import re
 import statistics
 from struct import error as StructError, pack, unpack_from
 import sys
-from typing import Any, cast
+from typing import Any, NoReturn, TypeVar, cast, overload
 from urllib.parse import urlencode as urllib_urlencode
 import weakref

@@ -92,6 +92,8 @@ _COLLECTABLE_STATE_ATTRIBUTES = {
     "name",
 }

+_T = TypeVar("_T")
+
 ALL_STATES_RATE_LIMIT = timedelta(minutes=1)
 DOMAIN_STATES_RATE_LIMIT = timedelta(seconds=1)

@@ -1375,7 +1389,7 @@ def utcnow(hass: HomeAssistant) -> datetime:
     return dt_util.utcnow()


-def raise_no_default(function, value):
+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(

homeassistant/helpers/template.py Outdated Show resolved Hide resolved
homeassistant/helpers/template.py Outdated Show resolved Hide resolved
Copy link
Contributor

@emontnemery emontnemery left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @pyos, this is a great first contribution to the project 🚀

@emontnemery emontnemery changed the title Add boolean template filter and function Add bool template filter and function Jun 28, 2022
Copy link
Member

@frenck frenck left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great! Many will love this 👍

@frenck frenck merged commit 0e9164b into home-assistant:dev Jun 28, 2022
@github-actions github-actions bot locked and limited conversation to collaborators Jun 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
cla-signed core new-feature noteworthy Marks a PR as noteworthy and should be in the release notes (in case it normally would not appear)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants