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.
| Category | Operators |
|---|---|
| Comparison | ==, !=, <, <=, >, >= |
| Boolean | and, or, not |
| Membership | in, not in |
| Identity | is, is not |
| Arithmetic | +, -, *, /, %, ** |
| String concatenation | + |
| Indexing | x[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:
| Function | Where | Purpose |
|---|---|---|
print(*args) | scripts, validation | Write to the platform’s diagnostic panel. No effect in production runs. |
fail("msg") | scripts, validation | Reject the answer with an error message. Most useful inside validation:. See Validation. |
endSurvey(status?) | scripts | End the interview with a status ("complete", "terminate", "quotafull"). Positional string only; no-arg form defaults to "terminate". See Survey status & redirect. |
redirectUrl(url) | scripts | Send the respondent’s browser to an external URL. Auto-appends rid / token / projectid. See Survey status & redirect. |
quota(groupId, cellCode) | scripts | Read quota cell state set up in the Quota Builder. Returns .count, .target, .remaining, .isFull, .isOpen. See Quotas. |
q(baseName) / q(baseName, code) | scripts | String-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
| Object | Purpose |
|---|---|
request | Read 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:
importstatements (any) —math,random,re,datetimeare 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.)lambdain any position — usedef helper(x): ...instead- List / dict / set comprehensions and generator expressions — use an explicit
forloop withresult.append(...) - Decorators (
@something) classdefinitionswithstatementsasync/await/yieldbreak/continue— restructure with a flag or earlyreturnfrom adef//floor-division — useint(a / b)ormath.floor(a / b)- f-strings (
f"...") — use"..." + str(x)or"%s" % x - Walrus
:= s.replace(...)on strings — usere.sub(...)instead
See Python essentials for the canonical equivalents.
See also
- Scripts —
- script:blocks - Python essentials — language subset reference
- Patterns — copy-pasteable cookbook
- Q.* accessors — what
Q.somethingreturns - Collections — methods on
.selected - Validation —
validation:blocks share the same Python subset