I have a python script I wrote that I want to be able to take in either a single entity id or a list of entity ids to match home assistant syntax for other services. So I want to coerce the argument into a list, but there doesn’t seem to be a good way to check if the argument is a string or a list.
I can’t do type(ids) == 'list' because type isn’t available in the python script. isinstance(ids, list) doesn’t work since list isn’t accepted in the second argument. Anybody know of a way to coerce the arg into a list?
{{ "foo" | list == "foo" }}
{{ [1,2,3] | list == [1,2,3] }}
{{ ["foo","bar","bas"] | list == ["foo","bar","bas"] }}
{# {{ 123 | list == 123 }} #}
Force it to a list and if it is still the same as what you got then it’s a list. It won’t work for a single number input, but you’re dealing with entity IDs which are strings, so it should be fine.
Thanks for the tips, but that’s using templating jinja2, specifically this is in a python script. Is there a way to evaluate an arbitrary jinja2 template in python script?
After some more trial and error, I found a way to do it, but is rather inefficient for large lists since it coverts the whole list. I can check if str(arg) == arg. Lists will be converted as "['element1']" whereas a string would be unchanged.
I missed that you’re writing a Python script. Somehow I read you were looking for something equivalent to what you could do in Python when making an HA scriot. Regardless, what you’re doing is essentially the same kind of trick as I suggested. In the end it’s a trick and it won’t be efficient, as you’ve seen. I don’t know why those two built-ins aren’t available. In fact, I’m wondering how would one even restrict that.
In Python, if you’re working in an environment where certain built-in functions like type or isinstance are not available (which can be the case in some restricted or sandboxed environments), you can still check if an argument is a string or a list and coerce it into a list using other approaches. Here are a couple of methods you might find useful:
Using str and Exception Handling: Python treats strings as sequences, just like lists. However, applying list-specific methods on a string will raise an exception. You can use this behavior to differentiate between a string and a list.