pysxLearn by building

Foundations · Lesson 4 of 28

Derived values and operators

Express dependent values once and let their dependencies drive updates.

A total, a filter result and a validation condition are usually consequences of source state. Storing each consequence independently creates extra work: every handler must remember to update them all. A derived value records the sources read by its callback and recomputes from those sources.

Named helpers build reactive expressions too: gt(quantity, 3) returns a signal that says whether the quantity exceeds three. Python's not always returns a plain boolean, so use not_(threshold) to keep the opposite condition reactive. Alternatively, put ordinary Python inside derived, such as derived(lambda: not threshold()).

Understand the moving parts

The calculator below has quantity as a source and total as a consequence. Its threshold uses gt to read that source, and within_limit uses not_ to read the threshold. Changing only quantity updates the total and both conditions. Pass the signals into the template without calling them so the outputs stay live.

Walk through the code

from pysx import Fragment, derived, gt, not_, pysx, signal


def app() -> Fragment:
    quantity = signal(1)
    total = derived(lambda: quantity() * 12)
    threshold = gt(quantity, 3)
    within_limit = not_(threshold)

    def increase(_: object) -> None:
        quantity.update(lambda value: value + 1)

    return pysx(t"""
        button(id="quantity-increase" onClick={increase}): "Add one item"
        p: "Quantity: "
        output(id="quantity"): {quantity}
        p: "Total at 12 per item: "
        output(id="total"): {total}
        p: "Quantity exceeds three: "
        output(id="threshold"): {threshold}
        p: "Quantity at most three: "
        output(id="within-limit"): {within_limit}
    """)

quantity starts at 1. The total callback reads it and multiplies by 12; the reactive helper gt(quantity, 3) drives the threshold, while not_(threshold) drives its opposite. Add one item writes only the source. At quantity 4 the total is 48, the threshold is True and within_limit is False, without setting any dependent value.

Try it live

Increase quantity past three, observe both conditions, then reset. Explain why the total and conditions need no separate set calls.

What to observe

The total is quantity times 12. At quantity 4 the conditions flip to True and False; reset returns quantity to 1, total to 12 and the conditions to False and True.

Quantity:

1

Total at 12 per item:

12

Quantity exceeds three:

False

Quantity at most three:

True

Take this with you

Store sources; derive consequences. Choose helpers when Python forces a primitive.