Skip to content

Formula DSL

Calculated measures, having predicates, and style-rule conditions all speak the same small expression language. It is deliberately safe: the Python side parses with ast against a strict allow-list and the @tensorgrid/core port reimplements the identical semantics, so the same string computes the same value in the engine and in the browser — and neither can execute arbitrary code.

from dash_tensor_grid import build_grid
payload = build_grid(sales, {
"rows": ["region"],
"measures": {"revenue": "sum", "cost": "sum"},
"calculated": {
"margin": "(revenue - cost) / revenue", # safe division: /0 -> NaN -> "—"
"health": "clamp((revenue - cost) / revenue, 0, 1)",
"unit_cost": "coalesce(cost / revenue, 0)", # null-handling helper
"grade": "'A' if margin > 0.4 else 'B'", # ternary + chained compares
},
"formats": {"revenue": "currency:USD", "margin": "percentage:1"},
})
  • Operators+ - * / // % **, unary -/+. Division is safe: a zero divisor yields NaN (rendered as ) instead of raising; // and % follow Python’s divisor sign.
  • Comparisons< <= > >= == !=, including chained (0 < margin < 1).
  • Booleanand / or / not; and/or return an operand (not a bool), matching Python truthiness (0, '', null falsy).
  • Ternarya if condition else b.
  • Functionsabs, min, max, round (banker’s), sqrt, floor, ceil, log, log10, exp, pow, plus the null-aware helpers coalesce(...) (first non-null), clamp(x, lo, hi), and sign(x).

The allow-list is enforced at compile time, before any value is evaluated. Attribute access (x.y), subscripting (x[0]), lambdas, comprehensions, and calls to anything outside the fixed function table are rejected up front with a FormulaError — so a formula from a config file or an end user can never reach out of its sandbox. The engine (Python ast) and the browser port share this guarantee byte-for-byte.

  • For aggregation-side expressions (a base measure), Dash exposes {"sql": "..."} and DSL aggregation helpers like wavg(price, units) / sum_if(revenue, region == 'EMEA'). Those build a Polars expression and stay server-side.
  • Need to actually run Python? A {"python": "pkg:fn"} / {"python_code": "..."} measure runs code and is refused unless you pass allow_code=True — enable it only for configs you trust.
  • Where these expressions plug in: calculated measures and style rules.