pysxLearn by building

Compose an interface · Lesson 9 of 28

Lists and nested iteration

Render live nested collections and keep each handler attached to its own row.

A Python comprehension evaluated while building a template is a snapshot. A reactive list region instead reads its collection as that collection changes. This distinction matters when adding, removing or reordering records.

Use each for live rows and each_indexed when the current position is part of the display. Nested rows need their own stable keys and correctly captured parent values; a callback must not accidentally use the last loop variable.

Understand the moving parts

A row renderer is an ordinary function. Its parameter provides one record and a closure can retain that record's identifier. The library owns reconciliation of the returned fragment. A stable key names the record, not its current index.

In the demo, reverse the groups before selecting a nested child. The selection readout should still name the clicked group's child. Adding a group affects the live region, while the snapshot count remains the count taken at setup.

Walk through the code

from pysx import Fragment, each, pysx, signal


def app() -> Fragment:
    groups = signal(["Read", "Build"])
    snapshot = len(groups())
    selected = signal("None")

    def group(name: str) -> Fragment:
        def child(label: str) -> Fragment:
            def choose(_: object) -> None:
                selected.set(f"{name} / {label}")

            choice_id = name + "-" + label

            return pysx(t"""
                button(data-choice={choice_id} onClick={choose}): {label}
            """)

        return pysx(t"""
            li(data-group={name})
                h3: {name}
                div: {each(("first", "second"), child, key=str)}
        """)

    def add(_: object) -> None:
        if len(groups()) < 12:
            groups.update(lambda rows: [*rows, f"Group {len(rows) + 1}"])

    def reverse(_: object) -> None:
        groups.update(lambda rows: list(reversed(rows)))

    return pysx(t"""
        div:
            button(id="group-add" onClick={add}): "Add group"
            button(id="group-reverse" onClick={reverse}): "Reverse groups"
        ul(id="groups"): {each(groups, group, key=str)}
        output(id="group-selection"): {selected}
        p: "Snapshot group count: " {snapshot}
    """)

groups is passed uncalled to each. Every nested handler closes over its own group name and label. Add and reverse update the live list; snapshot stays at its initial length of two.

Try it live

Add a group, reverse the groups and select a child from the original first group.

What to observe

The list changes immediately, the snapshot stays fixed and selection names the correct group.

  • Read

  • Build

None

Snapshot group count: 2

Take this with you

A live list is an owned region, not a comprehension rerun by magic.