Jeriks
March 14, 2023, 9:07pm
1
I’m looking for a way to apply math to every element in a list.
I have a sensor with an attribute numbers
that looks something like this (an array of numbers):
[1,2,3,4,5,6,7]
I’ve made a custom sensor, also with an attribute numbers
, and I want to fill it with the same values as the other sensor except have every value offset by some number, for example 1.
If list comprehension was a thing, I would do it like this:
{% set numbers = states['sensor.example_sensor'].attributes.numbers%}
{{ [n+1 for n in numbers] }}
I’ve looked around for a way to do it but I couldn’t find anything that would do the trick.
I can do this:
{% set numbers = states['sensor.example_sensor'].attributes.numbers %}
{% for n in numbers %}
{{n +1}}
{% endfor %}
Which would output:
2
3
4
5
6
7
8
But that’s just printing the numbers across multiple lines, not a proper array
Is there a way to do something similar to list comprehension in jinja? Or maybe some way I can make my example solution format the output as an array instead of printing the numbers across multiple lines?
123
(Taras)
March 14, 2023, 9:27pm
2
You have to build a new list containing the incremented values.
{% set ns = namespace(x=[]) %}
{% for i in state_attr('sensor.example_sensor', 'numbers') %}
{% set ns.x = ns.x + [i + 1] %}
{% endfor %}
{{ ns.x }}
Example
1 Like
Jeriks
March 14, 2023, 9:35pm
3
Awesome! Thank you!
I hadn’t thought about using {% set %} inside the loop, but that works perfectly
1 Like
123
(Taras)
March 14, 2023, 9:37pm
4
The following PR might be of interest to you. Its author is attempting to enhance Home Assistant’s implementation of Jinja2 by allowing for a mutable list.
home-assistant:dev
← depoll:jinja-add-mutable
opened 06:45PM - 22 Feb 23 UTC
<!--
You are amazing! Thanks for contributing to our project!
Please, DO N… OT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
If your PR contains a breaking change for existing users, it is important
to tell them what breaks, how to make it work again and why we did this.
This piece of text is published with the release notes, so it helps if you
write it towards our users, not us.
Note: Remove this section if this PR is NOT a breaking change.
-->
## Proposed change
<!--
Describe the big picture of your changes here to communicate to the
maintainers why we should accept this pull request. If it fixes a bug
or resolves a feature request, be sure to link to that issue in the
additional information section.
-->
Breaking out #88575
Here, I've added the ability to create a mutable copy of a list or dictionary in jinja that you can directly modify (rather than rebuilding the list/dictionary element-by-element, which can turn an O(1) operation into an O(n) or O(n^2) operation). This requires two additions:
* `as_mutable` filter so that one can efficiently mutate a list or dictionary without rebuilding it from scratch in a loop
* Enabling the 'Expression Statement' [`do` extension](https://jinja.palletsprojects.com/en/3.0.x/extensions/#expression-statement) to make it possible to mutate lists/dicts.
All of this enables the following code:
```jinja2
{% set mutableDict = {} | as_mutable %}
{% do mutableDict.update({'foo': 'bar'}) %}
{% set mutableList = [] | as_mutable %}
{% do mutableList.append("baz") %}
{{ mutableDict }}
{{ mutableList }}
```
To produce the following output:
```
{'foo': 'bar'}
['baz']
```
I'm happy to update the documentation as well but wanted to first clear that this would be a welcome change.
## Type of change
<!--
What type of change does your PR introduce to Home Assistant?
NOTE: Please, check only 1! box!
If your PR requires multiple boxes to be checked, you'll most likely need to
split it into multiple PRs. This makes things easier and faster to code review.
-->
- [] Dependency upgrade
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [x] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests
## Additional information
<!--
Details are important, and help maintainers processing your PR.
Please be sure to fill out additional details, if applicable.
-->
- This PR fixes or closes issue: fixes #
- This PR is related to issue:
- Link to documentation pull request: https://github.com/home-assistant/home-assistant.io/pull/26437
## Checklist
<!--
Put an `x` in the boxes that apply. You can also fill these out after
creating the PR. If you're unsure about any of them, don't hesitate to ask.
We're here to help! This is simply a reminder of what we are going to look
for before merging your code.
-->
- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] The code has been formatted using Black (`black --fast homeassistant tests`)
- [x] Tests have been added to verify that the new code works.
If user exposed functionality or configuration variables are added/changed:
- [x] Documentation added/updated for [www.home-assistant.io][docs-repository]
If the code communicates with devices, web services, or third-party tools:
- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.
Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.
<!--
This project is very active and we have a high turnover of pull requests.
Unfortunately, the number of incoming pull requests is higher than what our
reviewers can review and merge so there is a long backlog of pull requests
waiting for review. You can help here!
By reviewing another pull request, you will help raise the code quality of
that pull request and the final review will be faster. This way the general
pace of pull request reviews will go up and your wait time will go down.
When picking a pull request to review, try to choose one that hasn't yet
been reviewed.
Thanks for helping out!
-->
To help with the load of incoming pull requests:
- [ ] I have reviewed two other [open pull requests][prs] in this repository.
[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure
<!--
Thank you for contributing <3
Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io
1 Like