A total is a relationship.
Price multiplied by quantity is a rule you want to state once. A formula gives it named inputs and a destination in Data. Other declarations can bind to that destination, so the calculation remains independent of where the result is displayed.
This is useful for estimates, counts, summaries and presentation decisions. Several formulas can form a readable chain: quantity and price produce a subtotal; the subtotal contributes to another result.
Choose the trigger as carefully as the expression.
Arguments with ^ trigger execution. Arguments with = are read when execution occurs. _init=True computes an initial result. In the gallery, total is reactive while one gross calculation reads the VAT rate without subscribing to it. Changing that rate alone therefore does not rerun that declaration.
That is a teaching choice, not a recommendation for every quotation: make all business dependencies reactive when that is what the workflow requires.
pane.dataFormula(
".total", "price * quantity",
price="^.price", quantity="^.quantity",
_init=True
)Read the explanation here. The working lesson and full contract are linked below.
Move reusable logic into a named method.
The short multiplication expression illustrates the mechanism. A reusable calculation belongs in Logic, referenced through func, with its inputs still visible in the declaration. Both forms execute browser behavior; a Python declaration does not turn its inline expression into Python.
A formula writes its result. A controller runs behavior and makes its own writes. Use the distinction to communicate intent to the next person reading the page.
Keep estimates and authoritative results distinct.
A local formula can give immediate feedback without a request. A price confirmed by a business service may follow different rules, availability or permissions. Label the local result as a preview when the service makes the final decision.
Exact financial arithmetic, currency policy and rounding require suitable types and explicit rules; the simple multiplication lesson is not a full pricing engine.