Patterns
Copy-pasteable cookbook of common script idioms — recoding to derived flags, randomising treatments once, summing across grids, capturing query params, defensive numeric arithmetic, gating with `def` helper functions. Snippet-style; lifted from real surveys.
Recoding into a derived flag
Re-bucket a multi-question selection into a smaller categorical hidden question for analysis.
- qid: Race
type: multi
text: Which best 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)
The script is idempotent — re-running it always produces the
same bucket from the same Race answer. Safe under navigation.
One-shot treatment assignment
Randomise a respondent into a treatment cell exactly once, even if they navigate back through the survey.
- qid: hTreatment
type: single
visibility: hide
text: Randomised treatment cell (1 = control, 2 = variant A, 3 = variant B)
options:
1: Control
2: Variant A
3: Variant B
- qid: hAssigned
type: single
visibility: hide
text: Has the treatment been assigned yet?
options:
1: Yes
- script: |
if hAssigned.value != 1:
hTreatment.set(random.choice([1, 2, 3]))
hAssigned.set(1)
The hidden hAssigned flag pins the assignment. First pass
randomises; subsequent passes see hAssigned == 1 and skip.
For an even split that doesn’t depend on random, hash the
respondent ID:
- script: |
if hAssigned.value != 1:
rid = request.param("rid")
bucket = (sum([ord(c) for c in rid]) % 3) + 1
hTreatment.set(bucket)
hAssigned.set(1)
(Note: list comprehensions aren’t supported, so the
sum([ord(c) for c in rid]) form needs the explicit-loop
equivalent — see below for the canonical pattern.)
Sum across a grid or list
Aggregate values across the rows of a numberList or
gridNumber.
- qid: QSpend
type: numberList
text: Allocate your monthly spend across these categories.
options: spendCategories
- script: |
total = 0
for c in QSpend.all:
total = total + (QSpend.row(c).value or 0)
hMonthlyTotal.set(total)
QSpend.all returns every code in the question’s authored
domain; QSpend.row(c).value reads each row’s number, with
or 0 coalescing unanswered rows to zero.
For a gridNumber, sum each row’s cell values via .values
(a collection that sum(...) understands), iterating over the
row codes you authored:
- script: |
total = 0
for r in [1, 2, 3]: # the row codes on QGrid
total = total + sum(QGrid.row(r).values)
hGridTotal.set(total)
There’s no Q.allRows / Q.allColumns accessor on
gridNumber — list the row (or column) codes explicitly. If
the row set is dynamic, build it once into a hidden helper or
a def-defined function and reuse it.
Counting matching selections
How many of a respondent’s selections fall into a known set:
- script: |
premium_codes = [1, 2, 3, 5, 8]
count = 0
for c in QBrand.selected:
if c in premium_codes:
count = count + 1
hPremiumOwned.set(count)
For “any” / “every” semantics, prefer the collection methods on the selection itself rather than rolling your own loop:
- script: |
if QBrand.selected.any([1, 2, 3]):
hAnyPremium.set(1)
if QBrand.selected.every([1, 2]):
hOwnsBoth.set(1)
Capturing query params at the start of the flow
Read identifying values from the entry URL and stash them in hidden questions so they fall into the export and become available to downstream logic via accessors.
- qid: PanelId
type: open
visibility: hide
text: Panel-supplied respondent ID from the entry URL's ?rid param
- qid: Source
type: open
visibility: hide
text: Traffic source code captured from the entry URL's ?source param
- script: |
PanelId.set(request.param("rid"))
Source.set(request.param("source").lower())
Place the - script: near the top of the flow so values are
available before any question references them. See
Query params.
Helper functions for masking and routing
When a routing condition or options.from: mask gets long,
move it into a def and reference the function from the
declarative property.
- script: |
def is_premium_buyer():
return Spend.value > 100 and BrandTier.value == 1
def relevant_brand_codes():
result = []
for c in QBrand.all:
if c in premium_codes() or QBrand.selected.any([c]):
result.append(c)
return result
def premium_codes():
return [1, 2, 3, 5, 8]
# Used downstream.
- if is_premium_buyer():
- qid: QPremiumPath
type: open
text: Tell us about your premium experience.
- qid: QShortlist
type: multi
text: Pick your shortlist.
options.from: relevant_brand_codes()
def-defined functions are reachable from every later script,
every - if <expr>: predicate, and every options.from: /
scale.from: expression.
Mid-flow termination
Screen out and bounce the respondent back to the panel:
- if Age.value < 18:
- script: |
endSurvey("terminate")
redirectUrl("https://panel.example.com/screenout")
endSurvey() (no args) defaults to "terminate", so for
screenouts you can shorten:
- if Age.value < 18:
- script: |
endSurvey()
redirectUrl("https://panel.example.com/screenout")
Defensive numeric arithmetic
number questions read as None when unanswered. Coalesce
with or 0 to keep arithmetic clean:
- script: |
total_spend = (HouseholdSpend.value or 0) + (PartnerSpend.value or 0) + (KidsSpend.value or 0)
hHouseholdTotal.set(total_spend)
Or guard upfront when the script shouldn’t run at all without a value:
- script: |
if not HouseholdSpend.answered:
return
hSpendBand.set(1 if HouseholdSpend.value < 100 else 2)
String building for redirect URLs
redirectUrl takes a single URL string. Build it up with
concatenation, splicing in question values:
- script: |
redirect_url = (
"https://sawtooth.example.com/conjoint"
+ "?project=42"
+ "&Qconcept=" + str(QConcept.value)
+ "&lang=" + QLang.value
+ "&gender=" + str(QGender.value)
)
redirectUrl(redirect_url)
str(...) coerces non-string values; QLang.value is already
a string for single/open questions.
Try / except around a setter
When a write might legitimately fail (rank validation, lookup
miss), wrap in try and recover:
- script: |
try:
QRank.set(rank_codes_from_upstream)
hRankSource.set("computed")
except Exception:
QRank.set([1, 2, 3]) # fallback ordering
hRankSource.set("default")
The error is still recorded for the platform’s diagnostic panel — the catch lets your script continue past it without the respondent seeing a failure page.
Carrying values forward across waves
When you receive a previous wave’s answer as a query param and want to seed the current survey with it:
- qid: QPrevBrand
type: single
text: Last wave you said your favourite brand was {{ QPrevBrandLabel.value }}. Still your favourite?
options:
1: Yes
2: No
- qid: QPrevBrandLabel
type: open
visibility: hide
text: Previous wave's brand label
- qid: QPrevBrandCode
type: number
visibility: hide
text: Previous wave's brand code
- script: |
QPrevBrandLabel.set(request.param("prev_brand_label"))
QPrevBrandCode.set(toInt(request.param("prev_brand_code")))
The label appears in the question text (via piping); the code is available for downstream conditions.
See also
- Scripts — full deep-dive on
- script: - Python essentials — language reference
- Built-ins & operators — every safe builtin and module
- Q.* accessors — read / write surface on questions
- Routing —
- if:flow blocks for gating scripts - Masking —
options.from:andscale.from:acceptdef-defined helpers