Scripting in Python

Python essentials

The language subset available inside `- script:` and `validation:` blocks. Statements, control flow, function definitions, the supported builtins and modules — what works, what's blocked, and the everyday equivalents for the things that aren't there. Aimed at programmers who already know Python; reference, not tutorial.

What “subset” means

The runtime executes a deliberately reduced version of Python. The shape of a script body should look familiar — if / elif / else, for, while, def, indentation-driven blocks — but several language features common in everyday Python are intentionally not implemented.

The subset is opinionated, not arbitrary: every blocked feature has a footgun (mutating closures, side-effects in comprehensions) or a security cost (eval, file I/O) or a performance cost (generators in tight loops) that doesn’t pay off in survey-author code.

Comments

Three comment forms, all Python-inert everywhere the DSL parses code — script bodies, validation:, and on flow / code headers themselves:

# A line comment on its own line.
- script: |
    # Line comment inside a script body.
    Q1.set(2)          # inline / trailing comment
    #[[
      Block comment — anything between `#[[` and `#]]`
      is stripped by the parser, including {{ pipe }} tokens
      and code samples.
    #]]
    Q2.set(3)

- if: Q3.value == 1    # trailing comment on a flow header
    - qid: Q4

The comment is stripped before the parser and the validator see the line, so:

  • {{ pipe tokens }} written inside a comment are ignored — no spurious “unknown identifier” errors on publish.
  • A trailing # comment on a - if …: header is not absorbed into the condition expression at runtime.
  • Comments in a validation: body don’t trip the validator engine.

Exception — respondent-facing text. In title: / text: / label: and other visible strings, # stays literal. title: "Item #{{ Q1.value }}" still validates the real pipe token; the # is displayed as-is.

Control flow

if / elif / else

Standard Python if statement. Indentation matters; mix in elif / else as needed.

if Age.value < 18:
    hAgeBand.set(1)
elif Age.value < 35:
    hAgeBand.set(2)
elif Age.value < 65:
    hAgeBand.set(3)
else:
    hAgeBand.set(4)

Don’t confuse the statement (above, valid Python inside a - script: body) with the flow block - if <expr>: (a YAML structural element that gates whole questions / scripts). See Routing for the three forms of if in the platform side by side.

for loops

Iterate over a collection. The most common case is iterating over a question’s selected codes:

total = 0
for code in QSpend.all:
    total = total + (QSpend.row(code).value or 0)

Tuple unpacking works in for headers:

for index, code in enumerate(QBrand.selected):
    print(index, code)

Starred targets (for *rest, last in pairs:) are not supported.

while

Standard while loop. Useful for early termination on a condition; rare in survey scripts but available.

i = 0
while i < 5:
    if QBrand.selected.any([i + 1]):
        break_index = i
    i = i + 1

break and continue are not supported — the runtime flags them as unsupported constructs. Restructure with a flag variable or an early return if you’re inside a def.

try / except / finally

Standard exception handling. Catch by base Exception:

try:
    QRank.set(rank_codes)
except Exception:
    QRank.set([1, 2, 3])
finally:
    print("attempt completed")

except Exception as e: works for binding the error to a variable. Multiple except clauses are supported.

Note: errors raised inside try are still recorded as runtime errors for platform visibility, even when caught. The catch lets your script continue past the failure; it doesn’t hide the diagnostic from QA.

def — function definitions

def works at the top of a script body. Functions defined in one script are callable from every subsequent script and from inline - if <expr>: predicates.

def is_premium_buyer():
    return Spend.value > 100 and BrandTier.value == 1

def household_total():
    return (Spend.value or 0) + (PartnerSpend.value or 0)

Then later in the flow:

- if is_premium_buyer():
    - qid: QPremiumPath
        ...

def accepts default arguments and keyword arguments. *args / **kwargs work. lambda is not supported — use def for any callable, even one-line ones.

What’s intentionally blocked

The runtime detects these and refuses to run the script — the error message names the construct so you know what to swap.

ConstructStatusUse instead
List / dict / set comprehensionsBlockedExplicit for loop with result.append(...).
Generator expressionsBlockedSame — explicit for loop.
lambdaBlockedTop-level def.
Decorators (@something)BlockedCall the wrapper explicitly.
class definitionsBlockedUse a dict or top-level functions.
with statementsBlockedThe runtime has no resources to manage.
async / await / yieldBlockedSynchronous logic only.
break / continueBlockedRestructure with a flag or early return.
// floor divisionBlockedint(a / b) or math.floor(a / b).
f-strings (f"...")Blocked"..." + str(x) or "%s" % x.
Walrus :=BlockedPlain assignment then condition.
import (any)BlockedThe four safe modules below are already in scope — call them directly.
File I/O / networkBlockedThe runtime is sandboxed.

The everyday equivalent for the most-missed feature — list comprehension — is the explicit append pattern:

# Standard Python (not supported):
even_codes = [c for c in QBrand.all if c % 2 == 0]

# Fieldbase equivalent:
even_codes = []
for c in QBrand.all:
    if c % 2 == 0:
        even_codes.append(c)

A bit more typing, no comprehension magic. The runtime is fast enough that the loop form has no measurable cost.

Indexing & slicing

Standard subscript syntax works. Negative indices and slices both translate cleanly:

codes = QBrand.selected
first = codes[0]
last = codes[-1]
first_two = codes[:2]
every_other = codes[::2]

Tuple unpacking

Works in for headers, in destructuring assignments, and in function returns:

a, b = (1, 2)

for k, v in pairs:
    print(k, v)

def split_first(xs):
    return xs[0], xs[1:]

head, rest = split_first(codes)

Starred targets aren’t supported, so:

# Not supported:
first, *rest = codes

# Equivalent:
first = codes[0]
rest = codes[1:]

Operators

Standard Python operators are available.

CategoryOperators
Comparison==, !=, <, <=, >, >=
Booleanand, or, not
Membershipin, not in
Identityis, is not
Arithmetic+, -, *, /, %, **
String concatenation+
Indexingx[0], x[-1], x[1:3]

/ is true division (always a float when both sides are int). For integer floor-division, write int(a / b) or math.floor(a / b) — // is rejected.

Safe builtins

Available without import. Categorised for readability; full reference lives in Built-ins & operators.

# Aggregate
len(x)              # length of sequence / collection
min(x)              # minimum value
max(x)              # maximum value
sum(x)              # sum
avg(x)              # arithmetic mean (platform addition)
sorted(x)           # new sorted list
range(start, end)   # iterable range
enumerate(x)        # (index, value) pairs
zip(a, b)           # parallel iteration
any(x)              # True if any element truthy
all(x)              # True if all elements truthy

# Constructors
set([1, 2, 3])
list(x)
dict(...)
tuple(x)

# Type conversion
str(x)              # to string
int(x)              # to integer
float(x)            # to float
bool(x)             # to boolean
isNumeric(x)        # platform: True if x parses as a number
toNumeric(x)        # platform: coerce to number, None if not parseable
toInt(x)            # platform: coerce to int
toString(x)         # platform: alias for str
parseInt(x)         # platform: parse string as int
parseFloat(x)       # platform: parse string as float

# Math
abs(x)
round(x)
round(x, n)

avg, isNumeric, toNumeric, toInt, toString, parseInt, parseFloat are platform additions, not standard Python builtins. They’re useful for the kinds of type-coercion work survey scripts often need.

Safe modules

Four standard modules are already available in every script and validation block. Reference them by name directly — import statements are blocked entirely, so don’t write import math; just call math.floor(x).

math.floor(x)
math.ceil(x)
math.sqrt(x)
math.pi
math.e

random.choice([1, 2, 3])
random.shuffle(my_list)         # in place
random.randint(0, 10)           # int in [0, 10] inclusive

re.match(pattern, text)
re.search(pattern, text)
re.fullmatch(pattern, text)
re.sub(pattern, replacement, text)
re.split(pattern, text)

datetime.datetime.now()
datetime.date.today()
datetime.timedelta(days=7)

Two notes:

  • random produces respondent-specific results that won’t reproduce on replay. Treatment assignments should be one-shot (gated by a hidden flag) so the same respondent doesn’t re-randomise on navigation.
  • re.fullmatch is the right choice for validation — re.match only anchors the start, leaving trailing characters through. ZIP / phone / email regexes nearly always want fullmatch.

String methods

Most everyday string methods work as you’d expect:

s.strip()
s.lower()
s.upper()
s.startswith("Q")
s.endswith(".")
s.split(",")        # one separator argument required
" " in s
len(s)

Two methods to watch:

  • s.replace(...) is blocked — use re.sub("a", "b", s) instead. The replacement runs through the regex engine so patterns work too.
  • s.split() requires exactly one separator argument. No arg form (s.split()) is rejected; use re.split(...) if you need whitespace-splitting semantics.

Defensive idioms

A handful of patterns appear in nearly every survey:

or 0 for unanswered numerics

total = (Age.value or 0) + (PartnerAge.value or 0)

Unanswered number questions read as None. Without or 0, the addition produces None (or raises). With or 0, missing values coalesce to zero.

if not Q.answered: early exit

if not Spend.answered:
    hSpendBand.set(0)
    return        # skip the rest of this function

# ... arithmetic that assumes Spend has a value ...

Better than threading or 0 through every reference, when an unanswered upstream question means downstream logic shouldn’t run at all.

Empty-string check, not is None

# request.param() returns "" for missing keys, never None.
if request.param("source") == "":
    hSourceMissing.set(1)

# Or — empty strings are falsey:
if not request.param("source"):
    hSourceMissing.set(1)

request.param(...) is a string-only API. Don’t compare its return against None. See Query params.

See also