Scripting in Python

Scripts

`- script: |` is a freestanding Python block in the flow. Use it for imperative side-effects — recoding answers, pre-filling hidden questions, computing derived flags, defining helper functions, terminating respondents. Scripts have no `qid`, no UI, just a body that runs as the runtime walks past.

What - script: is

A - script: block is a flow-level node carrying Python code. The runtime walks the flow and, when it reaches the script, executes the body — read whichever questions you need, write back to whichever questions you need, call helpers like endSurvey(...) or redirectUrl(...).

- script: |
    if Age.value < 18:
        hSegment.set("under_18")
    elif Age.value < 65:
        hSegment.set("adult")
    else:
        hSegment.set("senior")

There’s no qid, no text, no if: property — just the | literal block and the indented Python body. Scripts don’t render anything to the respondent; they only have side effects.

YAML shape

The header is exactly - script: |. Everything that should run as Python sits indented underneath.

- script: |
    print("hello")

Three rules to remember:

  • The | literal is required. Without it the indented lines are parsed as YAML, not as code.
  • No properties on the script itself. id: / qid: / if: are all rejected by the validator. To gate a script conditionally, wrap it in an - if <expr>: flow block instead.
  • Script doesn’t nest inside - block: or - page:. It’s a peer of pages, not a child. Place scripts at the top level of the flow, or inside - if: / - elif: / - else: / - loop:. The validator emits invalid-child-block if a script lives under a page or block.
# Right — script as a top-level peer.
- page:
    id: demographics
    questions: [...]

- script: |
    # Runs after the demographics page is collected.
    hAgeBand.set(1 if Age.value < 35 else 2)

# Right — gated by a flow-level if.
- if request.param("country") == "US":
    - script: |
        endSurvey("terminate")
        redirectUrl("https://panel.example.com/screenout")

# Wrong — script directly under page.questions.
- page:
    questions:
        - script: |        # validator rejects this
            ...

When scripts run

The runtime walks the flow during each render pass and executes every script it reaches. In practice that means a script runs when the respondent advances past it — they answer the last question before the script, click Next, and the script fires before the next page renders.

Re-execution on navigation

Each render pass walks the flow from the top, so scripts that sit upstream of the respondent’s current position get visited on every pass. The runtime guards against re-execution by checking whether any answered question sits between the script and the respondent’s current target — if so, the script is treated as already passed and skipped.

The guard isn’t perfect. Write idempotent scripts — overwrite values rather than appending to them. A pattern that re-runs cleanly:

# Idempotent — re-running this is a no-op.
- script: |
    hAgeBand.set(1 if Age.value < 35 else 2)

A pattern that breaks on replay:

# Don't — every pass adds another increment.
- script: |
    hVisits.set(hVisits.value + 1)

If a script truly must run only once (e.g. randomising a treatment assignment), gate it on a hidden flag:

- script: |
    if hAssigned.value != 1:
        hTreatment.set(random.choice([1, 2, 3]))
        hAssigned.set(1)

Set the flag at the end of the one-shot work; subsequent passes see hAssigned.value == 1 and skip.

What’s in scope

Every script body runs in a context that already has:

  • Question accessors — every qid is in scope as an accessor object. Read with .value / .selected / .row(N) etc. (full surface in Q.* accessors). Write with .set(...) / .add(...) / .remove(...) / .reset().
  • request — the URL proxy. request.url and request.param("key"). See Query params.
  • Runtime helpers — print(...) for debugging, fail("...") for validation rejections, endSurvey(...) and redirectUrl(...) for end-of-flow handoffs.
  • The Python subset — if / elif / else, for, while, try/except/finally, def, all the standard operators, plus the safe builtins and modules listed in Python essentials.

Writing values back

Scripts mostly exist to write values back to questions. The four mutators on a question accessor:

MethodAvailable onEffect
MethodAvailable onEffect
---------
Q.set(value)every type — single, multi, rank, open, number, openList, numberList, gridSingle, gridMulti, lookup, plus rows/cellsReplaces the answer with value. For multi, value is a list of codes.
Q.add(code)multi, gridMulti.row(N), lookupAdds a code to the selection.
Q.remove(code)multi, gridMulti.row(N), lookupRemoves a code from the selection.
Q.reset()every typeWipes the answer back to unanswered.

Fluent vs. write-terminal

The two mutation styles behave very differently in expressions — mixing them up silently produces a None variable that crashes on the next use.

Write-terminal methods on a question proxy — .set(...), .reset(), and quota(...).fill() — mutate state and return None. They’re meant to be called on their own line:

Q1.set(2)              # ✓ correct — call on its own line
Q1.reset()             # ✓ correct

x = Q1.set(2)          # ✗ wrong — x is None, not the question
y = Q1.reset()         # ✗ wrong — y is None
Q1.set(2).answered     # ✗ wrong — Q1.set(2) is None, no .answered

The validator catches the wrong form with the question-write-assign diagnostic.

Fluent methods on collections, sets, lists, and dicts — .add(), .remove(), .intersect(), .union(), .minus(), .discard(), .clear(), .append(), .extend(), .sort(), plus dict’s .set(key, value) — return self (or a new collection) and are safe to chain or assign:

s = S2.all.remove(3).add(5)         # ✓ chain
filtered = items.remove(99)         # ✓ capture the result

Mnemonic. If you’re mutating a question, the result is None — one statement per line. If you’re mutating a collection / list / dict / set, the result is the collection itself — chain freely.

The setters validate strictly:

- script: |
    Age.set(25)              # OK — number question, integer value
    Age.set("25")            # ERROR — number rejects strings
    Brand.set(2)             # OK — single, in-domain code
    Brand.set(99)            # ERROR — single rejects out-of-domain code
    QRank.set([1, 2, 3])     # OK — rank takes a numeric list
    QRank.set([1, 1, 2])     # ERROR — rank rejects duplicates

If a setter rejects, the runtime raises a catchable Exception. Most authors don’t catch — let the error surface during testing, fix the source. For cases where you genuinely want to attempt a write and recover, wrap in try/except:

- script: |
    try:
        QRank.set(rank_codes)
    except Exception:
        # Fall back to a default ordering.
        QRank.set([1, 2, 3])

Errors raised inside try are still recorded for platform visibility, even when caught — the catch lets your script continue, but the diagnostic still surfaces.

Hidden questions for bookkeeping

The everyday way to hold computed values: declare a hidden question with visibility: hide, then .set(...) to it from a script.

- qid: hSegment
    type: open
    visibility: hide
    text: Computed segment from age (under_18 / adult / senior)

- qid: Age
    type: number
    text: How old are you?
    min: 0

- script: |
    if Age.value < 18:
        hSegment.set("under_18")
    elif Age.value < 65:
        hSegment.set("adult")
    else:
        hSegment.set("senior")

The h prefix is convention only — it’s not enforced anywhere. Anyone reading the YAML sees hSegment and knows “this is a hidden bucket the script writes to”. Pick the convention that suits your team and apply it consistently.

A hidden question is just a regular question with visibility: hide. It still:

  • Lives in the export with the same column name as any other question
  • Reads through the normal Q.value / Q.selected accessors
  • Writes through .set / .add / .remove / .reset

Pick the question type that matches the value shape — open for arbitrary strings, single for a coded category, number for a numeric, multi for a set of codes.

Defining helper functions

def works inside a script. Helper functions defined in one script are reachable from every later script and from inline - if <expr>: predicates that follow.

- script: |
    def qualifies_for_store_followup():
        return MainStreamer.value == 1 and StoreVisits.value >= 3

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

# Used in a later condition.
- if qualifies_for_store_followup():
    - qid: QStoreFollowup
        type: open
        text: Tell us about your last store visit.

A useful pattern for masking expressions that get unwieldy: move the logic into a def in a top-level script, then reference the function from options.from: or if:.

Calling runtime helpers

The four helpers exposed in script context:

- script: |
    print("Debug:", hSegment.value, "|", Age.value)
    fail("Age looks wrong.")               # rejects with a custom message
    endSurvey("complete")                   # ends the interview
    redirectUrl("https://panel.example.com/end")
HelperPurposeNotes
print(...)Write to the platform’s diagnostic panel during testing.No effect in production runs; useful for sanity-checking variables.
fail("...")Reject the answer with a custom error message.Most useful inside validation: blocks; works in scripts too. See Validation.
endSurvey(...)End the interview with a status.See Survey status & redirect.
redirectUrl(...)Send the respondent’s browser to a URL.Suspended (non-terminal) before endSurvey; immediate (terminal) after.

endSurvey(...) and redirectUrl(...) are explicitly rejected inside flow predicates (- if endSurvey(...): errors with endsurv-in-condition). They must live inside a - script: body. See Survey status & redirect for the full contract.

Common shapes

Recoding into a hidden bucket

- qid: Race
    type: multi
    text: Which describes you? (Select all)
    options: raceList

- qid: hRaceBucket
    type: single
    visibility: hide
    text: Recoded race for analysis
    options:
        1: AAPI / White / Multiracial
        2: Hispanic / Latino
        3: Black

- script: |
    if Race.selected.any([2]):
        hRaceBucket.set(1)
    elif Race.selected.any([3, 4]):
        hRaceBucket.set(2)
    else:
        hRaceBucket.set(3)

Show the question with the full ethnicity list, but analyse against a smaller bucketed dimension downstream. The script runs once after Race is answered.

Capturing entry-URL params

- qid: PanelId
    type: open
    visibility: hide
    text: Panel-supplied respondent ID (?rid)

- script: |
    PanelId.set(request.param("rid"))

Place the script near the top of the flow so the value lands before any downstream question references it. See Query params for the full pattern.

Mid-flow termination on a screening rule

- if Age.value < 18 or request.param("country") != "US":
    - script: |
        endSurvey("terminate")
        redirectUrl("https://panel.example.com/screenout")

A flow-level - if: gates the entire script — only respondents who fail the rule reach endSurvey.

Defensive numeric arithmetic

- script: |
    total = (HouseholdSpend.value or 0) + (PartnerSpend.value or 0)
    hHouseholdTotal.set(total)

Unanswered number questions read as None, which doesn’t cooperate with arithmetic. The or 0 idiom coalesces None to zero. See Python essentials.

See also

  • Python essentials — the language subset available inside - script: and validation:
  • Patterns — copy-pasteable cookbook of common script idioms
  • Built-ins & operators — full builtins / modules / operators reference
  • Q.* accessors — what you can read and write from a script
  • Routing — - if: / - elif: / - else: flow blocks for gating scripts
  • Validation — validation: blocks share the same Python subset