custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
873 stars 46 forks source link

Inconsistent `map` behavior when compared with standard python interpreter: expected str instance, coroutine found #633

Closed jsamr closed 3 weeks ago

jsamr commented 3 weeks ago

Running this code with Python interpreter...

def entity_is_on_expr(entity):
    return f"{entity} == 'on'"

presence_sensors_entities = ['one', 'two']
presence_expressions = ' or '.join(map(entity_is_on_expr, presence_sensors_entities))

print(f"Join expression: {presence_expressions}")

... shows the following in the console:

Join expression: one == 'on' or two == 'on'

Which is what I would expect in pyscript. Unfortunately, I get a type error instead:

2024-09-08 09:12:58.014 ERROR (MainThread) [custom_components.pyscript.apps.autolight.startup] Exception in <apps.autolight.startup> line 39:
presence_expressions = ' or '.join(map(entity_is_on_expr, presence_sensors_entities))
^
TypeError: sequence item 0: expected str instance, coroutine found

Pyscript version 1.6.1

craigbarratt commented 3 weeks ago

Yes, map doesn't work correctly in pyscript because all functions in pyscript are async (coroutines), and map expects a regular function.

You should add a @pyscript_compile before the definition of entity_is_on_expr(), which should make it a regular function. See the docs.

jsamr commented 3 weeks ago

Just realized this after reading the section you mentioned above; @pyscript_compile did work; thanks!