htm.py icon indicating copy to clipboard operation
htm.py copied to clipboard

Scope issue when calling components from list comprehension

Open pauleveritt opened this issue 5 years ago • 1 comments

I'm trying to do (in viewdom) an example of looping using a list comprehension. I was combining this with docs about Context and avoiding passing a value (in this case, prefix) down the component tree:

def Todo(label, prefix):
    return html('<li>{prefix}{label}</li>')


def TodoList(prefix, todos):
    return html('<ul>{[Todo(label, prefix) for label in todos]}</ul>')

This gives:

usage/examples/componentsH.py:12: in TodoList
    return html('<ul>{[Todo(label, prefix) for label in todos]}</ul>')
../../.venv/lib/python3.8/site-packages/tagged/__init__.py:84: in __tag
    values.append(eval(expr, f_globals, f_locals))
:1: in <module>
    ???
:1: in <listcomp>
    ???
E   NameError: name 'prefix' is not defined

Should a value in the scope of a function be available to a list comprehension?

pauleveritt avatar Mar 29 '20 13:03 pauleveritt

Ah, seems that this is an issue in tagged that's probably going to be tricky to fix.

Meanwhile, I suggest you work around the issue by moving the list comprehension out of the template:

def TodoList(prefix, todos):
    items = [Todo(label, prefix) for label in todos]
    return html('<ul>{items}</ul>')

jviide avatar Apr 08 '20 22:04 jviide