Runtime & expressions

Builtins & operators

The full list of safe Python builtins, modules, operators, and runtime helpers available in Fieldbase expressions and scripts.

Operators

Standard Python operators are available.

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

/ is true division (always returns a float for ints). The // floor-division operator is rejected outright by the runtime — write int(a / b) or math.floor(a / b) instead.

Keywords

if   elif    else    for     while
try  except  finally as      in
is   def     return  pass    and
or   not     True    False   None
Exception

Plus the runtime helpers that the parser recognises by name:

endSurvey   redirectUrl   print   fail

Safe builtins

The full list of available built-in functions:

Sequence / aggregate

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

Constructors

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

Type conversion

str(x)              # to string
int(x)              # to integer
float(x)            # to float
bool(x)             # to boolean
isNumeric(x)        # True if x looks like a number
toNumeric(x)        # coerce to a number, returning None if not parseable
toInt(x)            # coerce to int
toString(x)         # alias for str
parseInt(x)         # parse a string as int
parseFloat(x)       # parse a string as float

Math

abs(x)              # absolute value
round(x)            # round to nearest int
round(x, n)         # round to n decimal places

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 calling math.floor(x) works, but import math errors at runtime.

math

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

random

random.choice([1, 2, 3])     # one element from the list
random.shuffle(x)            # shuffle in place
random.randint(0, 10)        # int in [0, 10]

Use carefully — random produces respondent-specific results that won’t reproduce when the survey is replayed.

re

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

For anything beyond exact-match validation, re is the tool. The .replace() method on strings is rejected outright by the runtime — use re.sub(pattern, replacement, text) for any string replacement.

datetime

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

String methods

Most common string methods work:

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

s.replace(...) is rejected by the runtime — use re.sub("a", "b", s) instead. s.split() with no argument is also rejected; pass the separator explicitly, or use re.split(...) for whitespace splitting.

Runtime helpers

Functions that aren’t standard Python but are exposed at runtime:

FunctionWherePurpose
print(*args)scripts, validationWrite to the platform’s diagnostic panel. No effect in production runs.
fail("msg")scripts, validationReject the answer with an error message. Most useful inside validation:. See Validation.
endSurvey(status?)scriptsEnd the interview with a status ("complete", "terminate", "quotafull"). Positional string only; no-arg form defaults to "terminate". See Survey status & redirect.
redirectUrl(url)scriptsSend the respondent’s browser to an external URL. Auto-appends rid / token / projectid. See Survey status & redirect.
quota(groupId, cellCode)scriptsRead quota cell state set up in the Quota Builder. Returns .count, .target, .remaining, .isFull, .isOpen. See Quotas.
q(baseName) / q(baseName, code)scriptsString-keyed lookup against the runtime context. q("QAge") returns the QAge proxy. With a second argument, the helper concatenates code onto baseName (no separator inserted) and returns whatever’s registered under that name — useful for reaching a specific loop iteration when the qid suffix is in a variable. Returns null on miss. See q() for dynamic qid lookup below.

q() for dynamic qid lookup

q(baseName) returns the runtime proxy for the question whose qid is baseName. q(baseName, code) concatenates code onto baseName and looks up that combined name. Both return null if no proxy is registered under the resulting name.

# Plain alias for a literal qid — equivalent to bare QAge.value
q("QAge").value

# Dynamic — when the suffix is computed at runtime
for c in brand_loop.all:
    q("QRating_", c).value      # reaches QRating_1, QRating_2, ...

The two-arg form does NOT insert a separator. q("QRating", 1) looks up QRating1 (no underscore), which is not the same as the looped-question accessor QRating_1. To reach a loop iteration whose suffix follows the underscore convention, supply the underscore yourself in baseName:

q("QRating_", c)            # ✓ resolves to QRating_1, QRating_2, ...
q("QRating", c)             # ✗ resolves to QRating1, QRating2, ... — wrong
q("QRating_" + str(c))      # ✓ same effect, single-arg form

For looped questions, the QRating_[c] Proxy form is usually the cleanest path. Reach for q() when the qid itself is a string you’ve computed (e.g. building the name from a configuration map) rather than a literal in your script.

Runtime objects

ObjectPurpose
requestRead the entry URL the respondent arrived on — request.url and request.param("key"). See Query params.
- qid: hPanelId
    type: open
    visibility: hide
    text: Panel-supplied respondent ID from the entry URL's ?rid param

- script: |
    # Capture the panel ID from the URL.
    hPanelId.set(request.param("rid"))

What’s blocked

The runtime is a Python subset. These don’t work:

  • import statements (any) — math, random, re, datetime are already in scope; reference them directly without an import
  • File I/O (open, read, write)
  • Network calls (urllib, requests)
  • eval, exec, compile
  • __ dunder access (x.__class__, __import__, etc.)
  • lambda in any position — use def helper(x): ... instead
  • List / dict / set comprehensions and generator expressions — use an explicit for loop with result.append(...)
  • Decorators (@something)
  • class definitions
  • with statements
  • async / await / yield
  • break / continue — restructure with a flag or early return from a def
  • // floor-division — use int(a / b) or math.floor(a / b)
  • f-strings (f"...") — use "..." + str(x) or "%s" % x
  • Walrus :=
  • s.replace(...) on strings — use re.sub(...) instead

See Python essentials for the canonical equivalents.

See also