In the MX8 platform, surveys are written in Python using the Survey class.
Surveys should always start with the code block:
from survey import Survey
s = Survey(**globals())
You can import other Python libraries that are part of the standard library, e.g. datetime and math, but not modules that are not in the standard library, like pandas.
Response value types
Question methods return typed response values such as StringResponse, IntResponse, ListResponse,
and DictResponse. These behave like the corresponding Python str, int, list, and dict values,
so they can be compared, indexed, and iterated normally. BoolResponse supports normal boolean checks.
Response values also retain survey metadata. Tags passed to a question are available through the
response's topics dictionary and as attributes:
answer = s.select_question(
"Which brand?",
options=["Acme", "Example"],
tags=s.tag(category="brand"),
)
if answer.category == "brand":
s.store_value("selected_brand", answer)
Every response value exposes is_valid and error_message. The response classes named in signatures
describe values returned by the survey runtime; survey scripts do not need to import those classes.
Survey
Survey class for creating surveys.
materials
@property
materials: MaterialsModel
Return canonical tables, adapting historical saved survey state at the boundary.
watermark_text
@property
watermark_text: str
Read secure-rendering settings on new and historical saved surveys.
exposure_sources
@property
exposure_sources: list[str]
Return the exposure sources used by the survey.
respondent
@property
respondent: Respondent
Return normalized context for the current respondent.
Use this property when survey logic needs to branch based on normalized respondent metadata supplied at launch time.
Automatic reporting
Reading a respondent field adds a calculated survey variable so that the value is available
in reporting. Its stable reporting ID is respondent_{field}, such as
respondent_device_type. Question names replace underscores with spaces, such as
Respondent device type. Repeated access uses the same reporting variable. languages
is reported as a multi-value field; an empty value is reported as an empty multi-value.
Other missing respondent fields are reported as empty strings.
The source field is added automatically when its launch-time name is available, so
survey authors do not need to access it explicitly for reporting.
Matching helpers such as is_country(...) and has_language(...) report the underlying
field they access. get_provider_metadata(...) does not automatically report arbitrary
provider values.
Available fields
The respondent context exposes:
source: source name captured at launch time, falling back to the source type.country: canonical MX8 country code, or None when unavailable.languages: tuple of canonical MX8 language codes in preference order.browser: browser family parsed from the user agent, or None.device: device family parsed from the user agent, or None.os: operating system family parsed from the user agent, or None.device_type: one of "mobile", "tablet", "pc", "bot", "other", or None.
Matching helpers
Use is_country(...), is_any_country(...), has_language(...), and
has_any_language(...) to match country or language values by code, name, or synonym.
Use get_provider_metadata(...) to read provider metadata values as strings.
Example
from survey import Survey
s = Survey(**globals())
if s.respondent.is_country("United States"):
s.select_question(
"Which region do you live in?",
options=["Northeast", "Midwest", "South", "West"],
tags=s.tag(country=s.respondent.country),
)
if s.respondent.device_type == "mobile":
s.show_message("Thanks for taking this on your phone.")
question_group
question_group(
question: str,
tags: dict[str, Any] | None = None,
id: str | None = None,
custom_validator: Callable[[list[Any]], str | None] | None = None,
) -> QuestionGroup
Display ordinary questions together, submitting each answer in declaration order.
Assignments in the block may only be read after the block. Each variable then holds its question's ordinary response type. Use independent text, numeric, select, multi-select, rating, NPS, ranking or text-highlighter calls. Multi-response text uses the text_list control. Nested groups and multi-step flows are not supported. A custom_validator receives one list of parsed field responses in declaration order and returns a group error or None. Groups with a custom validator require whole-group submission.
Response
A context manager collecting normal question calls.
Example
with s.question_group(
question="About you",
custom_validator=lambda values: "Ages must differ" if values[0] == values[1] else None,
):
age = s.numeric_question("Your age", min_max=(0, 120))
comparison_age = s.numeric_question("Comparison age", min_max=(0, 120))
s.store_value("Age next year", age + 1)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | Heading for the form. |
tags | dict[str, Any] | None | Shared tags for the contained questions and heading. |
id | str | None | Optional stable heading ID. Child IDs retain their normal behaviour. |
custom_validator | Callable[[list[Any]], str | None] | None | Validate the complete list of parsed field responses in declaration order. |
grid_question_group
grid_question_group(
question: str,
rows: Sequence[str | MediaItem] | Mapping[str, Sequence[str | MediaItem]],
row_name: str,
tags: dict[str, Any] | None = None,
id: str | None = None,
custom_validator: Callable[[list[Any]], str | None] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
) -> QuestionGroup
Repeat the same ordinary controls across rows, returning a dictionary per call.
Single-response text_question, numeric_question, select_question and multi_select_question calls, plus show_image and show_message, are supported.
Uses the question_group execution and UI contract. Each assigned variable is a DictResponse keyed by the original row strings, containing ordinary responses. Row context is available for piping and reporting. Submit in question declaration order, then row order, regardless of client layout. Values assigned inside the block can only be read after it completes. A custom_validator receives one declaration-ordered list whose entries are the same row-keyed DictResponse values returned by the contained calls.
Media rows and questions
Rows accept strings or media items, including grouped and mixed inputs. Set image_label_field
to the media attribute used for stable row labels. show_image_label=False hides media labels;
image_size sets row image dimensions. Responses, row piping, and reporting continue to use
the resolved row labels. Images on contained questions and choices retain their own media
settings independently of the row images.
Response
The same context manager as question_group, with row repetition.
Example
with s.grid_question_group(
question="About your children", rows=["Child 1", "Child 2"], row_name="child"
):
ages = s.numeric_question("Age of {child}", min_max=(0, 17))
names = s.text_question("Name of {child}")
s.store_value("First child age", ages["Child 1"])
Parameters
| Name | Type | Description |
|---|---|---|
question | str | Heading for the repeated form. |
rows | Sequence[str | MediaItem] | Mapping[str, Sequence[str | MediaItem]] | Rows as unique strings or media items, optionally grouped under subsection headings. |
row_name | str | Non-reserved identifier used for row piping and reporting. |
tags | dict[str, Any] | None | Shared tags for the contained questions and heading. |
id | str | None | Optional stable heading ID. Child IDs remain optional. |
custom_validator | Callable[[list[Any]], str | None] | None | Validate the complete list of parsed field responses in declaration order. Each field response is keyed by row. |
image_label_field | str | None | The metadata field to use as the label for media items. |
show_image_label | bool | Whether to show each media item's label alongside the image. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
style
@property
style: Literal['traditional', 'chat']
Return the style of the survey.
Can be either 'traditional' or 'chat' depending on the configuration of the survey theme.
disable_bot_detection
disable_bot_detection() -> None
Disable bot detection mechanisms for this survey.
Appropriate use
Use this method when respondents are interacting with an interviewer who completes the survey, rather than responding on their own devices at home or work.
Bot detection tradeoff
This disables bot detection for the whole survey. Only use it when the survey collection mode makes automated bot checks inappropriate.
tag
tag(tags: Mapping[str, Any] | None = None, /, **kwargs: Any) -> dict[str, Any]
Create tags for questions, piping, or temporary tag contexts.
Context manager use
When used in a with s.tag(...): block, the tags are attached to every question created
inside that block.
Direct use
When passed as tags=s.tag(...), the tags are attached only to that question.
Piping
Tags can also provide values for placeholders such as {brand} in question text.
Example
from survey import Survey
s = Survey(**globals())
# Using as a context manager
with s.tag(brand="Ford", category="SUV"):
s.text_question("What do you like about {brand} {category}s?")
s.numeric_question("How many {brand} {category}s have you owned?")
# Passing directly to a question
s.text_question(
"Why is {brand} your favorite?",
tags=s.tag(brand=brand_name),
)
# Reuse the metadata of a selected video section
result = s.play_video(video, dial="right")
for section in result.sections:
with s.tag(section.tags):
s.text_question("Why did your reaction change here?")
s.numeric_question("How strongly did you feel?", min_max=(1, 10))
Parameters
| Name | Type | Description |
|---|---|---|
tags | Mapping[str, Any] | None | Optional positional mapping, such as section.tags from a video response. |
standard_screener
standard_screener(
country: str | None = None,
name: str = 'GenPop',
id: str | None = None,
) -> None
Add a standard screener to the survey.
Available country/name combinations come from the screener registry. The screener adds its standard demographic questions and, where supported, national weighting targets.
Example
from survey import Survey
s = Survey(**globals())
s.standard_screener(country="GB", name="GenPop")
Parameters
| Name | Type | Description |
|---|---|---|
country | str | None | The country to use for the screener. This is the country code in the MX8 system. For example, "US" for the United States, "GB" for Great Britain, or "AU" for Australia. |
name | str | The name of the screener to use. This is the name of the screener in the MX8 system. The default is "GenPop". |
id | str | None | Optional stable identifier prefix for generated screener questions. If not set the question text is used. |
show_message
show_message(
message: str,
image: MediaItem | None = None,
require_response: bool = True,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
) -> StringResponse | BoolResponse | IntResponse | ListResponse | None
Show a message to the user.
Use a message for introductions, instructions or warnings. Respondents acknowledge it by default;
require_response=False allows execution to continue without acknowledgment.
Example
from survey import Survey
s = Survey(**globals())
s.show_message("Welcome! We will ask a few questions about your recent shopping experience.")
Parameters
| Name | Type | Description |
|---|---|---|
message | str | The message to present to the user |
image | MediaItem | None | An image to show with the message, from get_image() |
require_response | bool | Whether the user must acknowledge the message |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
get_consent
get_consent(
consent_text: str | None = None,
topic: str | None = None,
client: str | None = None,
image: MediaItem | None = None,
number_seconds: int = 0,
id: str | None = None,
) -> BoolResponse
Get consent for the survey.
Asks the user the standard MX8 consent question. Terminates the respondent if they do not agree to the consent.
Example
from survey import Survey
s = Survey(**globals())
s.get_consent()
Parameters
| Name | Type | Description |
|---|---|---|
consent_text | str | None | Custom consent text to show instead of the standard MX8 consent text. |
topic | str | None | Topic to display in the standard consent question. |
client | str | None | Client description to use in the standard consent question. |
image | MediaItem | None | Image to show with the consent question, from get_image(). |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
text_question
text_question(
question: str,
image: MediaItem | None = None,
default: str | list[str] | list[list[str]] | None = None,
short: bool = False,
recodes: dict[str, str] | None = None,
validation_instructions: str | None = None,
quality_threshold: int = 3,
termination_threshold: int = 1,
max_attempts: int = 3,
custom_validator: Callable[[str | list[str]], str | None] | None = None,
number_of_responses: int = 1,
min_responses: int | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image_size: tuple[int, int] | None = None,
dont_know_option: str = '',
) -> StringResponse | ListResponse
Add a text question to the survey.
Ask an open-ended question using a text input or a list of text inputs.
Clarification and termination
AI validation scores a single text response from 1 to 5. Below quality_threshold, the respondent
is asked to clarify. On the final allowed attempt, a score at or above termination_threshold
is accepted; a lower score terminates the survey. The default termination_threshold=1 accepts
every score on the final attempt. Supplying custom_validator bypasses AI validation.
Multiple responses
Multiple text inputs are supported in landscape orientation. AI validation is unavailable for
multiple responses: leave the AI thresholds and attempt count at their defaults and omit
validation_instructions. A custom validator may still validate the complete list. Defaults
must contain one entry per input, with at least min_responses nonblank entries.
Response
Returns a StringResponse for one input or a ListResponse for multiple inputs. An explicit
opt-out returns its label, or a singleton list containing the label for multiple inputs, and
bypasses AI quality validation.
Example
from survey import Survey
s = Survey(**globals())
s.text_question("What did you enjoy about the experience?")
s.text_question(
"Name up to three car brands.",
number_of_responses=3,
min_responses=1,
default=["Ford", "", ""],
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
image | MediaItem | None | An image to show with the question, from get_image(). |
default | str | list[str] | list[list[str]] | None | The answer to use during simulation. For one response, pass a string or a list of candidate answers. For multiple responses, pass one full list of answers or a list of candidate lists. If omitted, simulation uses generated text. |
short | bool | whether to use a short text input field |
recodes | dict[str, str] | None | response mappings to use when reporting this question |
validation_instructions | str | None | a string describing AI validation rules for the question. Responses are scored on a scale of 1 to 5. |
quality_threshold | int | the normal minimum passing score on a scale of 1 to 5; defaults to 3 |
termination_threshold | int | the minimum score accepted on the final attempt; a lower score terminates the survey. Defaults to 1, which prevents score-based termination. |
max_attempts | int | the maximum number of attempts before applying termination_threshold |
custom_validator | Callable[[str | list[str]], str | None] | None | function called with the parsed response (a string for one response or a list of strings for multiple responses); return an error message to reject it, otherwise None |
number_of_responses | int | the number of responses to collect. Only supported in landscape orientation. |
min_responses | int | None | the minimum number of responses to collect. Only supported in landscape orientation. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
dont_know_option | str | optional explicit question-level opt-out label |
image_highlighter_question
image_highlighter_question(
question: str,
image: MediaItem,
color: str = '#FFFF00',
min_highlights: int = 1,
max_highlights: int | None = None,
default: list[dict[str, float]] | str | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
image_size: tuple[int, int] | None = None,
) -> ImageHighlighterResponse
Ask the respondent to highlight rectangular areas of an image. Each question uses one highlight color and one intent, such as highlighting areas they like. Use ordinary question tags to describe that intent.
Set image_size=(width, height) to request an image bounding box in pixels. If omitted,
the default bounding box is 600 by 600 pixels.
Use an uncropped source image. Cropped image items are rejected because selections use source-image coordinates. Crops can be displayed in ordinary follow-up questions.
Coordinates are normalized from 0 to 1 across the full image, with (0, 0) at the top left.
Each rectangle contains finite numeric x, y, width and height values. Dimensions must be positive and the
whole rectangle must fit within the image. Overlapping and repeated rectangles are allowed.
Response
Returns an ImageHighlighterResponse, which behaves like a ListResponse of coordinate strings.
Each string contains x,y,width,height, for example 0.1,0.2,0.3,0.25, without rounding
the captured coordinates. Read validated geometry using answer.rectangles, a tuple of typed ImageRectangle values.
For example, answer.rectangles[0].x is the first rectangle's normalized horizontal origin.
Object submissions and the serialized strings used in simulation/replay have the same
validated rectangle schema.
Raw exports, including SPSS, retain the four numeric coordinate values. Coordinates are not exported as categorical choices. Coded region results use the usual coded exports while retaining the original raw selections.
answer.selection_state is selected, empty, or opt_out. Setting min_highlights=0
allows an accepted empty list. An explicit opt-out returns its label as a singleton list
and has no rectangles. Skipped or missing answers have no saved response.
Capture retains full-precision geometry and the attachment filename as the ordinary
file_name topic. An authored file_name tag must match the attachment; a conflicting
value is rejected. Identical and overlapping rectangles retain their submitted order.
A new submitted answer replaces the previous selection set.
Example
from survey import Survey
s = Survey(**globals())
answer = s.image_highlighter_question(
"Highlight the areas you like.",
image=s.get_image("Creative"),
image_size=(1200, 800),
color="#00AA55",
min_highlights=0,
max_highlights=5,
dont_know_option="Nothing to highlight",
tags=s.tag(sentiment="like"),
default=[{"x": 0.1, "y": 0.2, "width": 0.3, "height": 0.25}],
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
image | MediaItem | the image attachment to highlight |
color | str | one six-digit highlight color |
min_highlights | int | minimum rectangle count; zero permits an accepted empty answer |
max_highlights | int | None | maximum rectangle count; None sets no upper limit |
default | list[dict[str, float]] | str | None | simulation rectangles with x, y, width and height, or the explicit opt-out label |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | optional explicit question-level opt-out label |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
qualitative_text_question
qualitative_text_question(
question: str,
instructions: str | None = None,
max_follow_ups: int = 3,
default: str | list[str] | None = None,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
) -> StringResponse
Run a bounded qualitative interview starting from one open question.
The opening answer is returned as a StringResponse. AI-generated follow-up answers are stored
as additional string responses with the same reporting ID and ordered transcript metadata.
The tags prompt and turn_index are reserved for that metadata.
Interview flow
After each answered turn, the interview may finish or ask another question, up to
max_follow_ups. An explicit opt-out stores its label and ends the interview without another
AI probe. The researcher instructions guide probing and are not respondent-facing copy.
Example
from survey import Survey
s = Survey(**globals())
opening = s.qualitative_text_question(
"What makes choosing a current account difficult?",
instructions="Understand the moments that create uncertainty and the trade-offs people make.",
max_follow_ups=3,
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | Required respondent-facing opening question. |
instructions | str | None | Optional researcher brief used only to guide AI probing. |
max_follow_ups | int | Maximum number of AI-generated questions after the opening turn. |
default | str | list[str] | None | The answer to use during simulation, or a list of candidate answers. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier shared as the reporting ID for every interview turn. |
dont_know_option | str | Optional explicit opt-out label, available on every interview turn. |
text_highlighter_question
text_highlighter_question(
question: str,
text_to_highlight: str,
color: str = '#FFFF00',
default: str | list[str] | list[list[str]] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
) -> ListResponse
Add a text highlighter question to the survey.
Ask the respondent to highlight one or more parts of the supplied text. Each highlight must be a nonempty, case-sensitive substring. Repeated or overlapping highlights are supported.
Response
Returns a ListResponse containing the selected substrings. An explicit opt-out returns a
singleton list containing its label, even when the label does not occur in the source text.
Example
from survey import Survey
s = Survey(**globals())
s.text_highlighter_question(
"Highlight the parts you find most interesting.",
text_to_highlight="The quick brown fox jumps over the lazy dog.",
color="#FFFF00",
default=["quick brown fox"],
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
text_to_highlight | str | the text that the respondent will highlight parts of |
color | str | highlight color as exactly six hexadecimal digits prefixed by #, for example #FFFF00; hexadecimal letter case is ignored. |
default | str | list[str] | list[list[str]] | None | Highlights to use during simulation. Pass a string for one highlight, a list of strings for one answer, or a list of candidate lists. If omitted, simulation uses random highlights. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | optional explicit question-level opt-out label |
numeric_question
numeric_question(
question: str,
image: MediaItem | None = None,
min_max: tuple[int, int] = (1, 10),
default: int | str | list[int] | list[str] | list[int | str] | None = None,
recodes: dict[str, str] | None = None,
style: Literal['input', 'button'] = 'input',
custom_validator: Callable[[int], str | None] | Callable[[int | str], str | None] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image_size: tuple[int, int] | None = None,
input_prefix: str | None = None,
input_suffix: str | None = None,
dont_know_option: str = '',
) -> IntResponse | StringResponse
Add a numeric question to the survey.
Collect an integer between the inclusive bounds in min_max.
Range recodes and buttons
Input-style recodes map numeric ranges to reported labels. Percentage keys describe positions
within the authored numeric range, rather than percentages of respondents. Use keys such as
"18-25" for an inclusive range, "65+" for an open-ended range, or "0-30%" and "75%+"
for percentages of the scale.
Button style requires explicit finite ranges, ordered and contiguous, covering all of min_max.
Each selected button returns its integer midpoint. Open-ended or percentage ranges cannot define
buttons. Input adornments are display-only and apply to input style.
Response
Returns an IntResponse, or a StringResponse containing the configured opt-out label. A custom
validator receives that parsed integer or label. Without a default, simulation samples a value
from the configured range or button values.
Example
from survey import Survey
s = Survey(**globals())
s.numeric_question(
"What is your monthly rent, in pounds?",
min_max=(0, 10000),
input_prefix="£",
input_suffix=" per month",
)
s.numeric_question(
"How old are you?",
min_max=(18, 100),
style="button",
recodes={"18-25": "18–25", "26-54": "26–54", "55-74": "55–74", "75-100": "75+"},
)
Percentage recode example
s.numeric_question(
"How many times have you visited our website?",
min_max=(0, 100),
recodes={"0-30%": "Low", "31-70%": "Medium", "71-100%": "High"},
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
image | MediaItem | None | An image to show with the question, from get_image(). |
min_max | tuple[int, int] | the inclusive minimum and maximum numeric values allowed |
default | int | str | list[int] | list[str] | list[int | str] | None | The answer to use during simulation: a number, the opt-out label, or a list of candidate answers. |
recodes | dict[str, str] | None | response mappings to use when reporting this question |
style | Literal['input', 'button'] | "input" for numeric entry or "button" for recode range buttons |
custom_validator | Callable[[int], str | None] | Callable[[int | str], str | None] | None | validates the integer answer or opt-out label; return an error message to reject it, otherwise None |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
input_prefix | str | None | optional display text before the numeric input; input-style questions only |
input_suffix | str | None | optional display text after the numeric input; input-style questions only |
dont_know_option | str | optional non-numeric opt-out label |
select_question
select_question(
question: str,
options: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
image: MediaItem | None = None,
randomize: bool = False,
other_options: list[str] | None = None,
disabled_options: list[str] | None = None,
fixed_options: list[str] | None = None,
specify_option: str | None = None,
specify_text: str = 'Please specify',
default: str | list[str] | None = None,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[str | int], str | None] | None = None,
skip_empty: bool = False,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
style: Literal['default', 'button', 'list', 'dropdown'] = 'default',
sorted: Literal['ascending', 'descending'] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
) -> StringResponse | IntResponse
Add a multiple-choice question to the survey.
The respondent chooses exactly one option. Response recodes affect reporting; survey logic still receives the selected option text.
Response
Returns a StringResponse, or an IntResponse when sorted enables numeric reporting using
option order. Sorted reporting cannot be combined with randomized options or specify-other.
Example
from survey import Survey
s = Survey(**globals())
transport = s.select_question(
"Which transport do you use most often?",
options=["Car", "Bus", "Train", "Bicycle"],
recodes={"Car": "private", "Bus": "public", "Train": "public", "Bicycle": "active"},
)
s.text_question(
"What do you like about using {transport}?",
tags=s.tag(transport=transport),
)
Pipe a write-in answer into a follow-up
When a respondent enters their own answer through specify_option, the typed text is available as
provider.specified_option. Use getattr to fall back to the selected option label when there is no write-in.
from survey import Survey
s = Survey(**globals())
provider = s.select_question(
"Who is your home internet provider?",
options=["Spectrum", "Verizon"],
specify_option="Other (please specify)",
)
provider_name = getattr(provider, "specified_option", provider)
s.select_question(
"How long have you had home internet with {provider}?",
options=["Less than a year", "1 to 3 years", "More than 3 years"],
tags=s.tag(provider=provider_name),
)
If the respondent types “Google Fiber,” the follow-up shows “Google Fiber.” If they select “Verizon,” it shows “Verizon.”
Custom validation example
s.select_question(
"For this attention check, please select Train.",
options=["Car", "Bus", "Train"],
custom_validator=lambda answer: "Please select Train." if answer != "Train" else None,
default="Train",
)
Randomization
Set randomize=True to randomize the order of the options.
fixed_options remain fixed at the end when the other options are randomized.
Sorted reporting cannot be combined with option randomization or specify-other.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
options | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Options as strings/media. Use a dict to group into subsections, e.g. {'Positive': ['Good', 'Great']}. |
image | MediaItem | None | An image to show with the question, from get_image(). |
randomize | bool | Whether to randomize the order of the options. |
other_options | list[str] | None | Additional options to present to the respondent. |
disabled_options | list[str] | None | Options that cannot be selected. |
fixed_options | list[str] | None | Options to keep at the end when the remaining options are randomized. |
specify_option | str | None | An option that lets the respondent enter their own answer. |
specify_text | str | Text to show when the respondent selects specify_option. |
default | str | list[str] | None | The answer to use during simulation, or a list of candidate answers from which one is chosen. If omitted, an answer is chosen at random. |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
custom_validator | Callable[[str | int], str | None] | None | Function called with the parsed selection (an integer when sorted is set); return an error message to reject it, otherwise None. |
skip_empty | bool | Skip the question when no options are available. |
image_label_field | str | None | The metadata field to use as the label for media items. |
show_image_label | bool | Whether to show each media item's label alongside the image. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
style | Literal['default', 'button', 'list', 'dropdown'] | presentation style for the options. |
sorted | Literal['ascending', 'descending'] | None | Optional reporting sort direction, either "ascending" or "descending". When set, reporting stores numeric scale values using option order while the respondent UI remains a select question. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
multi_select_question
multi_select_question(
question: str,
options: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
max_options: int | None = None,
image: MediaItem | None = None,
randomize: bool = False,
other_options: list[str] | None = None,
disabled_options: list[str] | None = None,
fixed_options: list[str] | None = None,
exclusive_options: list[str] | None = None,
specify_option: str | None = None,
specify_text: str = 'Please specify',
default: list[str] | list[list[str]] | None = None,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[list[str]], str | None] | None = None,
skip_empty: bool = False,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
style: Literal['default', 'button', 'list', 'dropdown'] = 'default',
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
) -> ListResponse
Add a multi-select question to the survey.
The respondent chooses one or more options. Fixed, exclusive, disabled and other option lists can
add choices that are not in the main options list.
Response
Returns a ListResponse containing selected option strings. Recodes affect reporting rather than
the values returned to survey logic.
Example
from survey import Survey
s = Survey(**globals())
enjoyment = s.multi_select_question(
"What did you enjoy about the experience?",
options=["The food", "The service", "The atmosphere"],
fixed_options=["Other"],
exclusive_options=["Other"],
recodes={"The food": "food", "The service": "service", "The atmosphere": "atmosphere", "Other": "other"},
)
if "Other" in enjoyment:
s.text_question("What else did you enjoy about the experience?")
Candidate selection example
s.multi_select_question(
"Which transport do you use?",
options=["Car", "Bus", "Train"],
default=[["Car"], ["Bus", "Train"]],
)
Custom validation example
s.multi_select_question(
"Please select both Bus and Train for this attention check.",
options=["Car", "Bus", "Train"],
custom_validator=lambda answers: "Please select Bus and Train." if set(answers) != {"Bus", "Train"} else None,
default=["Bus", "Train"],
)
Randomization
Set randomize=True to randomize the order of the options.
fixed_options remain fixed at the end when the other options are randomized.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
options | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Options as strings/media. Use a dict to group into subsections, e.g. {'Positive': ['Good', 'Great']}. |
max_options | int | None | the maximum number of options to be selected, defaults to all options |
image | MediaItem | None | An image to show with the question, from get_image(). |
randomize | bool | Whether to randomize the order of the options. |
other_options | list[str] | None | Additional options to present to the respondent. |
disabled_options | list[str] | None | Options that cannot be selected. |
fixed_options | list[str] | None | Options to keep at the end when the remaining options are randomized. |
exclusive_options | list[str] | None | Options that cannot be combined with other selected options. |
specify_option | str | None | An option that lets the respondent enter their own answer. |
specify_text | str | Text to show when the respondent selects specify_option. |
default | list[str] | list[list[str]] | None | The selection to use during simulation. Pass a list of choices or a list of candidate selections. If omitted, choices are selected at random. |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
custom_validator | Callable[[list[str]], str | None] | None | Function called with the parsed list of selections; return an error message to reject it, otherwise None. |
skip_empty | bool | Skip the question when no options are available. |
image_label_field | str | None | The metadata field to use as the label for media items. |
show_image_label | bool | Whether to show each media item's label alongside the image. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
style | Literal['default', 'button', 'list', 'dropdown'] | presentation style for the options. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
grid_select_question
grid_select_question(
question: str,
rows: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
row_name: str,
options: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
style: Literal['button', 'radio'] = 'radio',
randomize: bool = False,
randomize_options: bool = False,
other_options: list[str] | None = None,
fixed_options: list[str] | None = None,
specify_option: str | None = None,
specify_text: str = 'Please specify',
image: MediaItem | None = None,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[dict[str, str | int]], str | None] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
skip_empty: bool = False,
default: dict[str, str | list[str]] | list[dict[str, str | list[str]]] | None = None,
sorted: Literal['ascending', 'descending'] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
specify_row: str | None = None,
specify_row_text: str = 'Please specify',
) -> DictResponse
Add a grid select question to the survey.
The respondent chooses one option per row. Defaults use row keys; a per-row list supplies candidate answers, sampled once at creation, whether or not sorted reporting is enabled.
Respondents with prefer_open_end_text=True answer one row at a time. Other respondents
receive a native grid in both portrait and landscape layouts.
Set specify_row to an authored row such as "Other activity" and optionally set
specify_row_text to ask for its label. The authored row remains the response key and reporting
topic. The supplied label is available as response["Other activity"].specified_row and as the
specified_row reporting topic alongside the answer. It must contain non-whitespace text.
The specify_option independently collects a supplied answer option.
Submit the row's ordinary answer and supplied label separately through
response_json, for example [{"answer": "Often", "specified_row": "Kayaking"}] for a
single specified row. Other rows keep their existing answer values in the array.
Response and validation
Returns a DictResponse keyed by row, containing the ordinary select responses. Sorted reporting
uses integer values. Custom validators receive the complete parsed grid. The default validator
flags more than two identical substantive row answers, excluding explicit opt-outs; providing a
custom validator replaces that check.
Example
from survey import Survey
s = Survey(**globals())
s.grid_select_question(
"Rate these product aspects.",
rows=["Quality", "Price", "Service"],
row_name="Product Aspect",
options=["Poor", "Fair", "Good", "Very Good", "Excellent"],
default={"Quality": "Good", "Price": ["Fair", "Good"], "Service": "Excellent"},
)
Row and option media
Rows and options can contain media items and ordinary text together. Set image_label_field
to the media attribute used for stable labels. Images on each axis remain independent, including
when a row and an option share the same label. image_size applies to the media, and
show_image_label=False hides labels for media entries while preserving ordinary text options.
Both native grids and individual row choices retain their option images and presentation settings.
Selection values, disabled/exclusive options, defaults, reporting identities, and randomization
keep their existing semantics.
Randomization
Set randomize=True to randomize the order of the rows.
Set randomize_options=True to randomize the order of the options.
fixed_options remain fixed at the end when the other options are randomized.
Sorted reporting cannot be combined with option randomization or specify-other.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
rows | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Rows as strings/media. Use a dict to group into subsections, e.g. {'Work Environment': ['Lighting', 'Noise']}. |
row_name | str | Label to use for each row in topics. |
options | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Options as strings/media. Use a dict to group into subsections, e.g. {'Positive': ['Good', 'Great']}. |
style | Literal['button', 'radio'] | The style of the question ("button" or "radio"). Defaults to "radio". |
randomize | bool | Whether to randomize the order of the rows. |
randomize_options | bool | Whether to randomize the order of the options. |
other_options | list[str] | None | Additional options to present to the respondent. |
fixed_options | list[str] | None | Options to keep at the end when the remaining options are randomized. |
specify_option | str | None | An option that lets the respondent enter their own answer. |
specify_text | str | Text to show when the respondent selects specify_option. |
image | MediaItem | None | An image to show with the question, from get_image(). |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
custom_validator | Callable[[dict[str, str | int]], str | None] | None | function called with the complete parsed grid; sorted response values use integers. Return an error message to reject the response, otherwise None. |
image_label_field | str | None | The metadata field to use as the stable label for grid media items. |
show_image_label | bool | Whether to show labels alongside grid images. Text-only entries remain visible. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
skip_empty | bool | Skip the question when no rows or options are available. |
default | dict[str, str | list[str]] | list[dict[str, str | list[str]]] | None | Answers to use during simulation, keyed by row, or a list of candidate dictionaries. Per-row lists supply candidate answers. |
sorted | Literal['ascending', 'descending'] | None | Optional reporting sort direction, either "ascending" or "descending". When set, reporting stores numeric scale values using option order while the respondent UI remains a grid select question. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | Optional per-row response label for respondents who cannot choose an option. |
specify_row | str | None | Authored row that accepts a respondent-supplied label. |
specify_row_text | str | Prompt for the supplied row label. |
grid_multi_select_question
grid_multi_select_question(
question: str,
rows: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
row_name: str,
options: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
style: Literal['button', 'checkbox'] = 'checkbox',
randomize: bool = False,
randomize_options: bool = False,
other_options: list[str] | None = None,
fixed_options: list[str] | None = None,
exclusive_options: list[str] | None = None,
specify_option: str | None = None,
specify_text: str = 'Please specify',
image: MediaItem | None = None,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[dict[str, list[str]]], str | None] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
skip_empty: bool = False,
default: dict[str, list[str]] | list[dict[str, list[str]]] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
specify_row: str | None = None,
specify_row_text: str = 'Please specify',
) -> DictResponse
Add a grid multi-select question to the survey.
The respondent chooses one or more options per row. A default dictionary contains one complete selection list for every row; a list of dictionaries supplies candidate complete grids.
Set specify_row to an authored row and optionally set specify_row_text to ask for its label.
The authored row remains the response key and reporting topic. The supplied label is available
as response["Other activity"].specified_row and as the specified_row reporting topic.
It must contain non-whitespace text. The specify_option independently collects
a supplied answer option.
Response and validation
Returns a DictResponse keyed by row, with a ListResponse of selected options for each row.
The configured opt-out is exclusive within its row. Custom validators receive the complete parsed
grid. Without one, a repeated substantive selection across more than two rows triggers the
straight-line warning; opt-out rows are excluded.
Example
from survey import Survey
s = Survey(**globals())
s.grid_multi_select_question(
"What do you associate with these brands? Select all that apply.",
rows=["Coke", "Pepsi", "Fanta"],
row_name="Brand",
options=["Tasty", "Refreshing", "Good value"],
default={"Coke": ["Tasty", "Refreshing"], "Pepsi": ["Good value"], "Fanta": ["Tasty"]},
)
Row and option media
Rows and options can contain media items and ordinary text together. Set image_label_field
to the media attribute used for stable labels. Images on each axis remain independent, including
when a row and an option share the same label. image_size applies to the media, and
show_image_label=False hides labels for media entries while preserving ordinary text options.
Both native grids and individual row choices retain their option images and presentation settings.
Selection values, disabled/exclusive options, defaults, reporting identities, and randomization
keep their existing semantics.
Randomization
Set randomize=True to randomize the order of the rows.
Set randomize_options=True to randomize the order of the options.
fixed_options remain fixed at the end when the other options are randomized.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
rows | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Rows as strings/media. Use a dict to group into subsections, e.g. {'Work Environment': ['Lighting', 'Noise']}. |
row_name | str | Label to use for each row in topics. |
options | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Options as strings/media. Use a dict to group into subsections, e.g. {'Positive': ['Good', 'Great']}. |
style | Literal['button', 'checkbox'] | the question style, either "button" or "checkbox"; defaults to "checkbox" |
randomize | bool | Whether to randomize the order of the rows. |
randomize_options | bool | Whether to randomize the order of the options. |
other_options | list[str] | None | Additional options to present to the respondent. |
fixed_options | list[str] | None | Options to keep at the end when the remaining options are randomized. |
exclusive_options | list[str] | None | Options that cannot be combined with other selected options. |
specify_option | str | None | An option that lets the respondent enter their own answer. |
specify_text | str | Text to show when the respondent selects specify_option. |
image | MediaItem | None | An image to show with the question, from get_image(). |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
custom_validator | Callable[[dict[str, list[str]]], str | None] | None | function called with the complete parsed grid; return an error message to reject the response, otherwise None |
image_label_field | str | None | The metadata field to use as the stable label for grid media items. |
show_image_label | bool | Whether to show labels alongside grid images. Text-only entries remain visible. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
skip_empty | bool | Skip the question when no rows or options are available. |
default | dict[str, list[str]] | list[dict[str, list[str]]] | None | Selections to use during simulation, keyed by row, or a list of candidate dictionaries. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | optional exclusive response label for each row |
specify_row | str | None | Authored row that accepts a respondent-supplied label. |
specify_row_text | str | Prompt for the supplied row label. |
grid_rating_question
grid_rating_question(
question: str,
rows: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
row_name: str,
image: MediaItem | None = None,
number_of_points: int | None = None,
style: Literal['slider', 'button', 'star'] = 'slider',
first_point: int | None = None,
labels: Mapping[int, str | MediaItem] | None = None,
randomize: bool = False,
recodes: dict[str, str] | None = None,
dont_know_option: str = '',
skip_empty: bool = False,
custom_validator: Callable[[dict[str, int | str]], str | None] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
default: dict[str, int] | list[dict[str, int]] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
specify_row: str | None = None,
specify_row_text: str = 'Please specify',
) -> DictResponse
Add a grid rating question to the survey.
Rate each row on a numeric scale. Slider and button styles support 2–10 points; star style supports 2–5. These bounds apply to the resolved label span when the point count is omitted. Defaults contain a valid integer rating for every row, or a list of complete candidate dictionaries.
Set specify_row to an authored row and optionally set specify_row_text to ask for its label.
The authored row remains the response key and reporting topic. The supplied label is available
as response["Other activity"].specified_row and as the specified_row reporting topic
alongside the rating. It must contain non-whitespace text.
Response and validation
Returns a DictResponse keyed by row containing integer responses, with -999 for an explicit
opt-out after post-processing. Reporting uses the opt-out label. Custom validators receive the
complete parsed grid, with strings for opt-outs. The default check flags more than two identical
substantive ratings and excludes opt-outs; supplying a custom validator replaces it.
Example
from survey import Survey
s = Survey(**globals())
s.grid_rating_question(
"Rate these product aspects.",
rows=["Quality", "Price", "Service"],
row_name="Product Aspect",
number_of_points=5,
default={"Quality": 4, "Price": 3, "Service": 5},
)
Row and scale media
Rows and scale-point labels can contain media items and ordinary text together. Set
image_label_field to the media attribute supplying a stable text label. image_size sets
image dimensions, and show_image_label=False hides labels for images while preserving
ordinary text labels. Row and scale images remain independent even when their labels match.
Scale points remain numeric: image labels do not change selected values, defaults, reporting IDs, or recodes. Native grids, individual row questions, and saved row questions retain the same scale media. For example:
s.grid_rating_question(
"How much do you like each design?",
rows=[s.media[0], "Existing design"],
row_name="design",
labels={1: s.media[1], 5: "Like very much"},
image_label_field="name",
show_image_label=False,
image_size=(160, 120),
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
rows | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Rows as strings/media. Use a dict to group into subsections, e.g. {'Work Environment': ['Lighting', 'Noise']}. |
row_name | str | Label to use for each row in topics. |
image | MediaItem | None | An image to show with the question, from get_image(). |
number_of_points | int | None | The number of points on the scale for each row. If omitted, inferred from labels or defaults to 5. |
style | Literal['slider', 'button', 'star'] | the style of the question, either "slider", "button" or "star" |
first_point | int | None | the value of the first point, defaults to 1 or the first label |
labels | Mapping[int, str | MediaItem] | None | Scale-point labels as strings or media items, identified by image_label_field. |
randomize | bool | Whether to randomize the order of the rows. |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
dont_know_option | str | label to use for the don't-know option, if any. |
skip_empty | bool | if set to True, the question will be skipped if there are no rows |
custom_validator | Callable[[dict[str, int | str]], str | None] | None | function called with the complete parsed grid; don't-know rows use strings. Return an error message to reject the response, otherwise None. |
image_label_field | str | None | The metadata field to use as the stable label for grid media items. |
show_image_label | bool | Whether to show labels alongside grid images. Text-only entries remain visible. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
default | dict[str, int] | list[dict[str, int]] | None | Ratings to use during simulation, keyed by row, or a list of candidate dictionaries. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
specify_row | str | None | Authored row that accepts a respondent-supplied label. |
specify_row_text | str | Prompt for the supplied row label. |
grid_numeric_question
grid_numeric_question(
question: str,
rows: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
row_name: str,
columns: Sequence[str | MediaItem] | Mapping[str, Sequence[str | MediaItem]] | None = None,
column_name: str | None = None,
image: MediaItem | None = None,
min_max: tuple[int, int] = (1, 10),
randomize: bool = False,
randomize_columns: bool = False,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[dict[str, int | str | dict[str, int | str]]], str | None] | None = None,
autosum_columns: bool = False,
autosum_rows: bool = False,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
default: dict[str, int | str | dict[str, int | str]] | list[dict[str, int | str | dict[str, int | str]]] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
prefill: int | dict[str, int] | dict[str, dict[str, int]] | None = None,
specify_row: str | None = None,
specify_row_text: str = 'Please specify',
) -> DictResponse
Add a grid numeric question to the survey.
Collect an integer for each row, or for each row/column cell when both columns and column_name
are supplied. Every numeric value must be within the inclusive bounds in min_max.
Respondents with prefer_open_end_text=True answer one row or cell at a time. Other
respondents receive a native grid in both portrait and landscape layouts. The whole-grid
submission formats below apply to native grids; split questions accept ordinary scalar answers.
Set specify_row to an authored row and optionally set specify_row_text to ask for its label.
The authored row remains the response key and reporting topic. The supplied label is available
as response["Other activity"].specified_row for a numeric list, or on each cell for a numeric
grid, and as the specified_row reporting topic beside each answer. A numeric grid collects
one label for the row across its cells. Zero is an ordinary numeric answer and requires a label.
For a numeric grid, response_json contains column-first answer arrays;
each cell of the specified row carries {"answer": "0", "specified_row": "Kayaking"} with the
same label. For a numeric grid's text response, enter comma-separated row numbers for each column,
separate columns with tabs, then add the supplied row label as the final tab-separated value.
For example, two columns with rows Running and Other activity accept 1,0\t2,3\tKayaking.
Row and column media
Rows and columns accept strings and MediaItem objects, including mixtures and grouped inputs.
Set image_label_field to the media metadata attribute that supplies each stable label.
Labels must be unique within each axis; a row and a column can share a label without sharing
an image. show_image_label=False hides media labels while keeping ordinary text entries visible.
image_size applies to the images on both axes.
Numeric response, default, prefill, and reporting keys use the resolved labels, even when those labels are hidden or the axes are randomized. Media presentation does not add answer values.
The respondent API publishes every numeric column as an object with value, text, image,
and display_text, including text-only columns (image=None). This replaces the previous
string array and requires a UI supporting the object-column contract. There is no duplicate
column_items payload.
s.grid_numeric_question(
"Score each design",
rows=["Product A", "Product B"],
row_name="product",
columns=[s.media[0], "Existing design"],
column_name="design",
image_label_field="name",
show_image_label=False,
image_size=(160, 120),
min_max=(0, 10),
)
Defaults and prefill
Simulation defaults are complete row dictionaries, nested by column when columns are present, or candidate complete dictionaries. Additional default keys remain supported. Prefills are editable starting values shown to respondents: use one integer for every cell or a dictionary containing exactly the configured row/column keys. Prefills are independent of simulation defaults.
Response and validation
A row-only question returns a row-keyed DictResponse. With columns, engine v4+ returns
response[row][column]; older versions return response[column][row]. Defaults and prefills always
use row-first keys. Custom validators receive the complete parsed response using its public shape.
Without one, more than two identical substantive cell values trigger a straight-line warning.
Opt-outs are excluded, and a row cannot mix numeric and opt-out cells.
Autosum and recodes
autosum_rows and autosum_columns configure the UI and cannot both be enabled. The backend does
not enforce total equality. Numeric recodes use the same range/percentage syntax as numeric questions.
Example
from survey import Survey
s = Survey(**globals())
s.grid_numeric_question(
"How many hours do you spend on each activity on each day?",
rows=["Work", "Sleep", "Exercise"],
row_name="Activity",
columns=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
column_name="Day",
min_max=(0, 24),
prefill=0,
)
Randomization
Set randomize=True to randomize the order of the rows.
Set randomize_columns=True to randomize the order of the columns.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
rows | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Rows as strings/media. Use a dict to group into subsections, e.g. {'Work Environment': ['Lighting', 'Noise']}. |
row_name | str | Label to use for each row in topics. |
columns | Sequence[str | MediaItem] | Mapping[str, Sequence[str | MediaItem]] | None | Columns as strings or media items, identified by image_label_field. Use a dict to group into subsections, e.g. {'Time': ['Morning', 'Evening']}. Response and default keys use the resolved labels. |
column_name | str | None | the name of the column |
image | MediaItem | None | An image to show with the question, from get_image(). |
min_max | tuple[int, int] | the minimum and maximum values for the question |
randomize | bool | Whether to randomize the order of the rows. |
randomize_columns | bool | Whether to randomize the order of the columns. |
recodes | dict[str, str] | None | Response mappings to use when reporting this question. |
custom_validator | Callable[[dict[str, int | str | dict[str, int | str]]], str | None] | None | receives the complete parsed grid, including the configured non-numeric response when used; return an error message to reject the response, otherwise None |
autosum_columns | bool | whether to autosum the columns |
autosum_rows | bool | whether to autosum the rows |
image_label_field | str | None | The metadata field to use as the stable label for grid media items. |
show_image_label | bool | Whether to show labels alongside grid images. Text-only entries remain visible. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
default | dict[str, int | str | dict[str, int | str]] | list[dict[str, int | str | dict[str, int | str]]] | None | Answers to use during simulation, keyed by row (and then column where applicable), or a list of candidate dictionaries. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | optional non-numeric response label for each row |
prefill | int | dict[str, int] | dict[str, dict[str, int]] | None | respondent-visible starting values |
specify_row | str | None | Authored row that accepts a respondent-supplied label. |
specify_row_text | str | Prompt for the supplied row label. |
this_or_that_question
this_or_that_question(
question: str,
row_options: list[list[str | MediaItem]] | dict[str, list[list[str | MediaItem]]],
randomize: bool = False,
randomize_columns: bool = False,
default: dict[str, str | list[str]] | list[dict[str, str | list[str]]] | None = None,
recodes: dict[str, str] | None = None,
image: MediaItem | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
custom_validator: Callable[[dict[str, str]], str | None] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
dont_know_option: str = '',
) -> DictResponse
Add a this or that question to the survey.
Choose one of exactly two string or media options per row.
Example
from survey import Survey
s = Survey(**globals())
s.this_or_that_question("Which of the following do you prefer?",
row_options=[
["Apples", "Oranges"],
["Coke", "Pepsi"],
["Dogs", "Cats"],
["Winter", "Summer"]
])
Default values
Defaults are provided as a dictionary keyed by generated row ID (row1, row2, and so on)
in landscape orientation, or as a list of candidate dictionaries. Within each dictionary, a
list value supplies candidates from which one option is sampled once when the question is
created. The same one-based default keys are used in portrait orientation.
Return keys
The return value is a DictResponse of selected StringResponse values. Keys are one-based
(row1, row2, ...) in both landscape and portrait flows.
Media options
row_options may contain media items. Use image_label_field, show_image_label, and
image_size to control media option labels and display size.
Recodes
Recodes map each exact selected option string to its reported value, for example
{"Apples": "fruit", "Oranges": "fruit"}. Numeric ranges and percentage keys are not
supported for this choice-based question.
Custom validation
custom_validator runs on the parsed response. Return a string to reject it, or None to
accept it.
Randomization
Set randomize=True to randomize the order of the rows.
Set randomize_columns=True to randomize the order of the options.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
row_options | list[list[str | MediaItem]] | dict[str, list[list[str | MediaItem]]] | Pairs of strings/media. Use a dict to group into subsections, e.g. {'Work Environment': [['Light', 'Dark'], ['Quiet', 'Loud']]}. |
randomize | bool | Whether to randomize the order of the rows. |
randomize_columns | bool | Whether to randomize the order of the options. |
default | dict[str, str | list[str]] | list[dict[str, str | list[str]]] | None | Answers to use during simulation, keyed by row ID, or a list of candidate dictionaries. Per-row lists supply candidate answers. |
recodes | dict[str, str] | None | mappings from exact option strings to reported values |
image | MediaItem | None | An image to show with the question, from get_image(). |
image_label_field | str | None | the media field to use as the image label |
show_image_label | bool | whether to show the image label or just to show the image in the rows |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
custom_validator | Callable[[dict[str, str]], str | None] | None | function called with the complete parsed grid; return an error message to reject the response, otherwise None |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
dont_know_option | str | optional per-row response label for neither option |
this_or_that_rating_question
this_or_that_rating_question(
question: str,
row_options: Sequence[Sequence[str | MediaItem]] | Mapping[str, Sequence[Sequence[str | MediaItem]]],
row_name: str = 'scale',
number_of_points: int | None = None,
style: Literal['slider', 'button'] = 'slider',
first_point: int | None = None,
dont_know_option: str = '',
randomize: bool = False,
default: dict[str, int] | list[dict[str, int]] | None = None,
recodes: dict[str, str] | None = None,
image: MediaItem | None = None,
custom_validator: Callable[[dict[str, int | str]], str | None] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image_size: tuple[int, int] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
) -> DictResponse
Add a this or that rating question to the survey.
Rate between exactly two endpoints per row. Endpoints can be strings or media items.
For media, set image_label_field to the metadata field supplying its stable label.
The two labels in a row must differ. show_image_label controls image-label visibility;
image_size controls endpoint image dimensions. Mixed image/text endpoints are supported.
Endpoint media is published on the first/last numeric scale options, in native grids and individual row questions. Selected values remain numeric scale points. Generated row IDs, default keys, and reporting topics retain their existing meanings.
s.this_or_that_rating_question(
"Which design do you prefer?",
row_options=[[s.media[0], "Existing design"]],
image_label_field="name",
show_image_label=False,
image_size=(160, 120),
)
Example
from survey import Survey
s = Survey(**globals())
s.this_or_that_rating_question("Which of the following do you prefer?",
number_of_points=5,
row_options=[
["Apples", "Oranges"],
["Coke", "Pepsi"],
["Dogs", "Cats"],
["Winter", "Summer"]
])
Default values
Defaults are provided as a dictionary keyed by generated row ID (row1, row2, and so on),
or as a list of candidate dictionaries. The same stable keys are used in both orientations.
Return keys
The return value is a DictResponse keyed by generated row ID (row1, row2, and so on).
Endpoint names such as "Apples to Oranges" remain available as the row topic used for reporting.
Each value is the parsed IntResponse, or the don't-know sentinel after post-processing.
Style and scale
style, number_of_points, first_point, and row_options define the rating scale shown
for each row. Button and slider styles support between 2 and 10 points.
Recodes
Recodes map exact selected point strings such as "1" or "5" to reported values. They do
not use range or percentage syntax.
Custom validation
custom_validator runs on the parsed response. Return a string to reject it, or None to
accept it.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
row_options | Sequence[Sequence[str | MediaItem]] | Mapping[str, Sequence[Sequence[str | MediaItem]]] | Rating endpoints as string or media pairs, identified by image_label_field. Use a dict to group into subsections, e.g. {'Comfort': [['Cold', 'Hot']]}. |
row_name | str | the name of the row (default "scale") |
number_of_points | int | None | the number of points to rate the row on. Button and slider styles support between 2 and 10 points. Defaults to 5. |
style | Literal['slider', 'button'] | the style of the question, either "slider" or "button" |
first_point | int | None | the value of the first point, defaults to 1 |
dont_know_option | str | Optionally add a "Don't know" option to the question using this text. |
randomize | bool | Whether to randomize the order of the rows. |
default | dict[str, int] | list[dict[str, int]] | None | Ratings to use during simulation, keyed by row ID (such as row1), or a list of candidate dictionaries. |
recodes | dict[str, str] | None | mappings from exact point strings to reported values |
image | MediaItem | None | An image to show with the question, from get_image(). |
custom_validator | Callable[[dict[str, int | str]], str | None] | None | function called with the complete parsed grid; don't-know rows use strings. Return an error message to reject the response, otherwise None. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
image_label_field | str | None | The metadata field to use as the label for media items. |
show_image_label | bool | Whether to show each media item's label alongside the image. |
show_image
show_image(
image: MediaItem,
number_seconds: int = 5,
id: str | None = None,
image_size: tuple[int, int] | None = None,
) -> StringResponse | BoolResponse | IntResponse | ListResponse | None
Show an image to the respondent.
The continue control becomes available after the configured minimum delay. The image is not automatically dismissed at that time, and the respondent does not provide a substantive answer.
Example
from survey import Survey
s = Survey(**globals())
for media in s.media:
if media.is_image:
s.show_image(image=media, number_seconds=5)
Parameters
| Name | Type | Description |
|---|---|---|
image | MediaItem | the image to show |
number_seconds | int | the number of seconds to show the image |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | the bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
play_video
play_video(
video: MediaItem,
end_message: str = 'Thank you for watching the video!',
start_message: str = "Hit play when you're ready to watch the video.",
dial: str = 'none',
dial_labels: dict[int, str] | None = None,
dial_caption: str = 'Please adjust the slider to reflect your feelings as you watch the video.',
start_position: int | None = None,
number_seconds: int = 0,
id: str | None = None,
bucket_seconds: int = 5,
flat_tolerance: float = 0.05,
start_seconds: float | None = None,
end_seconds: float | None = None,
) -> VideoResponse
Play a video to the respondent.
This will play a video to the respondent and then present them with a message at the end, which defaults to "Thank you for watching the video!".
Video security
Secure videos use DRM and an IP-address watermark to discourage copying. Secure video links expire after 60 seconds.
Example
from survey import Survey
s = Survey(**globals())
for media in s.media.get_videos():
s.play_video(video=media)
# Now ask questions about the video.
Playback range
Use start_seconds and optional end_seconds to play a portion of the source video:
s.play_video(video=media, start_seconds=10.5, end_seconds=15.25)
Bounds are finite, non-negative seconds. The start must precede the end and both must fit
within the video's duration. If only the start is given, playback continues to the source end.
If only the end is given, playback begins at zero. A range must span at least one millisecond
after conversion to the UI's integer millisecond positions. Videos without either parameter
continue to play in full. start_position remains the initial dial value, not a playback time.
Dial testing
You can also add a dial to the video to allow the respondent to indicate their feelings as they watch the video. The dial can be set to one of the following values:
- "none" - no dial is shown
- "right" - a dial is shown on the right of the video
- "bottom" - a dial is shown at the bottom of the video
The dial defaults to a range of 0-100, with captions "Dislike", "Neutral", and "Like" but you can set the labels and caption for the dial using the dial_labels and dial_caption parameters.
Returned reaction sections
play_video returns a VideoResponse that behaves like the completion text and exposes
result.sections, a tuple of non-overlapping VideoSection objects in chronological order.
Each section has the following fields:
| Field | Type | Meaning |
|---|---|---|
value | float | Maximum for peaks, minimum for troughs, mean of whole-second dial values otherwise. |
start_seconds | float | Inclusive start of the section in seconds from the start of the video. |
end_seconds | float | Exclusive end of the section in seconds; may include a fractional second. |
rising | bool | The reaction rises through this section. |
falling | bool | The reaction falls through this section. |
flat | bool | The reaction forms a plateau within the configured tolerance. |
peak | bool | The reaction turns from rising to falling. |
trough | bool | The reaction turns from falling to rising. |
highest | bool | This section contains the highest dial value anywhere in the video. |
lowest | bool | This section contains the lowest dial value anywhere in the video. |
tags | dict[str, Any] | A fresh mapping of section metadata for tagging follow-up questions. |
value retains the authored dial units, such as 0-100; it is not normalized.
Exactly one of rising, falling, flat, peak, and trough is true for each section.
highest and lowest are independent flags: exactly one section has each flag, and the same
section can have both. Ties go to the earliest section. A local peak need not be the highest
section, and a local trough need not be the lowest.
section.tags contains start_seconds, end_seconds, value, section (one of "rising",
"falling", "flat", "peak", or "trough"), highest, and lowest. It also contains
question_id for the originating video question when that association is available.
Pass this mapping directly to a question or use it in a tag context:
result = s.play_video(video, dial="right")
for section in result.sections:
if section.highest:
with s.tag(section.tags):
s.text_question("What did you like about this part?")
elif section.falling:
s.text_question("Why did your reaction fall here?", tags=section.tags)
result.total_duration is the playback endpoint in seconds. result.get_value(offset_second)
returns the original dial value at the whole second containing the requested offset, carrying the
initial or previous value forward when it did not change. The offset must be a finite, non-negative
number before the video ends; fractional offsets are truncated with int(). Invalid offsets raise
ValueError. Videos without a dial have empty sections and no dial values.
Legacy completions without saved analysis have sections=(), total_duration=None, and
get_value(...)=None.
For a playback range, sections cover only the viewed portion while retaining positions in
seconds from the start of the source video.
Response
VideoResponse: Completion text with chronological sections, total_duration and get_value(offset_second). Legacy completions have no sections and an unavailable duration/trace.
Parameters
| Name | Type | Description |
|---|---|---|
video | MediaItem | the video to play, from get_video() |
end_message | str | the message to show the respondent at the end of the video |
start_message | str | the message to show the respondent at the start of the video |
dial | str | the position of the dial, either "none", "right", or "bottom", defaults to "none" |
dial_labels | dict[int, str] | None | the labels to show on the dial |
dial_caption | str | the caption to show above the dial |
start_position | int | None | starting value for the dial; defaults to the midpoint of the dial labels |
number_seconds | int | Seconds to wait before allowing the respondent to continue after the video. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
bucket_seconds | int | Reaction analysis interval in seconds. Must be a positive integer. Defaults to 5. |
flat_tolerance | float | Flatness threshold as a fraction of the authored dial range. A bucket is flat when its full min-max spread is strictly below this fraction of that range. Must be greater than zero and at most one. Defaults to 0.05 (5%). |
start_seconds | float | None | video playback start in seconds; defaults to zero |
end_seconds | float | None | optional video playback end in seconds |
show_embedded_media
show_embedded_media(question: str, url: str, duration: int) -> StringResponse
Embed external content from a URL in the survey.
The supported URL form is a YouTube watch URL on www.youtube.com with a nonempty v query
parameter. The delay is a non-negative integer number of seconds.
Example
from survey import Survey
s = Survey(**globals())
s.show_embedded_media("Watch this video", "https://www.youtube.com/watch?v=2gcsgfzqN8k", duration=231)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | the question to show above the embedded media |
url | str | the URL to embed in the survey |
duration | int | the number of seconds the respondent must wait before continuing |
location_question
location_question(
field: str = 'postal_code',
question: str = 'What is your zipcode?',
validation_field: str | None = 'city',
validation_question: str = 'Which city best describes where you live?',
report: Sequence[str] = ('region',),
strict: bool = False,
style: Literal['text', 'autocomplete'] = 'text',
country: str | None = None,
tags: dict[str, Any] | None = None,
default: str | list[str] | None = None,
number_options: int = 5,
number_seconds: int = 0,
id: str | None = None,
) -> StringResponse
Ask the respondent for their postal code and derive reportable location fields.
Capture currently supports field="postal_code" and style="text". Autocomplete remains
unsupported. Set validation_field=None to skip the optional confirmation question.
Report fields and IDs
report must be a nonempty sequence of fields supported by the selected country. The id applies
to derived report fields, rather than the capture question: one field uses id, while multiple
fields use {id}-{field}. Postal-code defaults must be valid for that country.
Strict respondent validation
With strict=True, a respondent is terminated when capture or confirmation leaves an active
validation warning. This is separate from validating the survey configuration.
Response
Returns the entered postal code as a StringResponse. Derived report fields are stored for
reporting and are not returned.
Example
from survey import Survey
s = Survey(**globals())
location = s.location_question(country="US", report=["region"])
Parameters
| Name | Type | Description |
|---|---|---|
question | str | the primary location question copy. |
validation_field | str | None | the location field to validate against. Use None to skip validation. |
validation_question | str | the validation follow-up question copy. |
report | Sequence[str] | nonempty sequence of country-supported fields to derive for reporting. |
strict | bool | whether to terminate when respondent-level location validation leaves a warning. |
country | str | None | optional country override. Defaults to respondent country or US. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
default | str | list[str] | None | The postal code to use during simulation, or a list of candidate postal codes. If omitted, simulation chooses a valid postal code for the selected country. |
number_options | int | the number of matching locations to show the respondent for validation. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
id | str | None | Optional stable identifier for one derived report field, or prefix when reporting multiple fields. If omitted, each derived field uses its generated question identity. |
quota
quota(
name: str,
criteria: bool,
quota: float = 0.0,
min_respondents: int = 0,
max_respondents: int | None = None,
) -> Quota
Create a quota line.
Use this to define an individual quota line that can be passed to s.set_quota().
Quota line only
This method only defines a quota line. Pass the returned quota to s.set_quota() to apply
quota logic to the survey.
Minimum and maximum respondents
A positive min_respondents replaces the percentage-derived completion target, even when
it is lower. If omitted or zero, the target is quota times the survey's target respondents,
truncated to a whole number. Targets are not redistributed across other lines.
max_respondents limits assignments under strict and quota-driven fielding. Under strict,
an explicit maximum replaces the completion target as the admission limit; without one,
the completion target is the limit. Under quota driven, a line without an explicit maximum
remains open until the survey completes. Respondent-driven fielding does not enforce line
maximums and can finish at the overall respondent target before line minimums are met.
A maximum does not change the line's completion target.
Example
from survey import Survey
s = Survey(**globals())
age = s.numeric_question(question="How old are you?",
min_max=(18, 100),
recodes={
"0-17": "Under 18",
"18-34": "18-34",
"35-54": "35-54",
"55-120": "55+"
})
gender = s.select_question(question="What is your gender?",
options=["Male", "Female"])
s.set_quota(
name="Quads",
quotas=[
s.quota("Younger Men", criteria=(age < 40) & (gender == "Male"), quota=0.25),
s.quota("Older Men", criteria=(age >= 40) & (gender == "Male"), quota=0.25),
s.quota("Younger Women", criteria=(age < 40) & (gender == "Female"), quota=0.25),
s.quota("Older Women", criteria=(age >= 40) & (gender == "Female"), quota=0.25)
]
)
You can also specify a minimum number of respondents that must be included in this quota line by passing the min_respondents parameter.
Example
from survey import Survey
s = Survey(**globals())
s.set_quota(
name="Age Quota",
quotas=[
s.quota("Under 18", criteria=(age < 18), quota=0.1, min_respondents=50),
s.quota("18-34", criteria=(age >= 18) & (age < 35), quota=0.3, min_respondents=100),
s.quota("35-54", criteria=(age >= 35) & (age < 55), quota=0.3, min_respondents=100),
s.quota("55+", criteria=(age >= 55), quota=0.3, min_respondents=100)
]
)
A group with only minimums and no quota proportions is not used for weighting. Its criteria still participate in quota qualification under the selected fielding strategy.
Parameters
| Name | Type | Description |
|---|---|---|
name | str | the name to give this quota line when it is reported |
criteria | bool | the boolean condition based on responses to other questions that the respondent must meet to be included in this quota line |
quota | float | the proportion of respondents that should fall into this quota |
min_respondents | int | positive completion target, replacing the percentage-derived target even when lower; omit or use zero to use the percentage-derived target |
max_respondents | int | None | optional assignment limit under strict and quota-driven fielding; not enforced under respondent-driven fielding |
set_quota
set_quota(name: str, quotas: list[Quota], exclusive: bool = True) -> QuotaResponse
Set a quota group based on a number of quota lines.
Takes a group of individual quotas from s.quota() and creates a quota group.
Termination behavior
Strict requires an open matching line in every quota group encountered. Quota driven and respondent driven require one in at least one group. Reaching a line's completion target does not necessarily stop assignments: strict uses an explicit maximum when set, otherwise the completion target; quota driven only enforces explicit maximums; respondent driven enforces neither. Strict and respondent driven also reject further respondents once the overall respondent target is reached.
Exclusive quotas
By default quotas are exclusive and each respondent fills one matching, open quota line,
chosen by the lowest ratio of completes to completion target. With exclusive=False,
respondents count toward every matching, open line. Each percentage target is still based
on the survey's target respondents, not multiplied by the number of lines.
Example
from survey import Survey
s = Survey(**globals())
age = s.numeric_question(question="How old are you?",
min_max=(18, 100),
recodes={
"0-17": "Under 18",
"18-34": "18-34",
"35-54": "35-54",
"55-120": "55+"
})
gender = s.select_question(question="What is your gender?",
options=["Male", "Female"])
# Check age and gender quotas
s.set_quota(
name="Quads",
quotas=[
s.quota("Younger Men", criteria=(age < 40) & (gender == "Male"), quota=0.25),
s.quota("Older Men", criteria=(age >= 40) & (gender == "Male"), quota=0.25),
s.quota("Younger Women", criteria=(age < 40) & (gender == "Female"), quota=0.25),
s.quota("Older Women", criteria=(age >= 40) & (gender == "Female"), quota=0.25)
]
)
Parameters
| Name | Type | Description |
|---|---|---|
name | str | the name of this group of quotas, for example "demos" |
quotas | list[Quota] | a list of quotas to be added, each created using s.quota() |
exclusive | bool | whether each respondent fills only one matching, open line; defaults to True. If False, respondents count toward every matching line that is open under the fielding strategy. |
get_least_filled
get_least_filled(
number: int,
from_list: list[Any],
quota: str,
group_by: Callable[[Any], object] | None = None,
) -> list[Any]
Get the least filled quotas from a list of elements in a quota.
Selects the least-filled items from a list for balanced follow-up questions.
One item per group
Pass group_by a function that returns a hashable key for each item. The method considers
the least-filled item in each group and returns up to number items from distinct groups.
Grouped selection balances by the number of completed respondents assigned to each item.
Each item must have a unique string representation. For media, this is the file name.
You can filter the candidate list per respondent and reuse the quota name to keep the
same counts for each creative. Newly seen creatives enter the shared cache on its next refresh.
assigned_images = s.get_least_filled(
2,
[ad for ad in s.get_images() if ad.survey_brand in assigned_brands],
"Image creative",
group_by=lambda ad: ad.survey_brand,
)
Selection only
This function returns the least-filled items from the list, but does not terminate the respondent based on quota state.
Counts represent assignments among completed respondents, not every item display or survey start. In-progress respondents do not reserve places, so several respondents can receive the same currently least-filled items before the counts update.
Terminating by quota
To terminate respondents based on quota state, use s.set_quota() to establish quotas.
Example
from survey import Survey
s = Survey(**globals())
brand_list = ['Acura', 'Alfa Romeo', 'Aston Martin', 'Audi', 'Bentley',
'BMW', 'Bugatti', 'Buick', 'Cadillac', 'Chevrolet', 'Chrysler',
'Citroen', 'Dodge', 'Ferrari', 'Fiat', 'Ford', 'Geely', 'Genesis',
'GMC', 'Honda', 'Hyundai', 'Infiniti', 'Jaguar', 'Jeep', 'Kia',
'Koenigsegg', 'Lamborghini', 'Land Rover', 'Lexus', 'Lincoln',
'Lotus', 'Maserati', 'Mazda', 'McLaren', 'Mercedes-Benz', 'Mini',
'Mitsubishi', 'Nissan', 'Pagani', 'Peugeot', 'Polestar', 'Porsche',
'Ram', 'Renault', 'Rolls-Royce', 'Subaru', 'Suzuki', 'Tesla', 'Toyota',
'Volkswagen', 'Volvo']
brands = s.get_least_filled(number=10,
from_list=brand_list,
quota="Brand familiarity")
familiar_brands = s.multi_select_question(
question="Which of the following car brands have you heard of?",
options=brands)
Parameters
| Name | Type | Description |
|---|---|---|
number | int | the number of items to return |
from_list | list[Any] | the list of items to choose from |
quota | str | the name of the quota to check against |
group_by | Callable[[Any], object] | None | optional function returning a group key for each item; select at most one item per group |
terminate
terminate(reason: str, number_seconds: int = 0) -> NoReturn
Terminate the survey.
Use this when the respondent does not qualify for a specific reason.
Immediate termination
This immediately stops the survey for the respondent.
Quota termination
Use s.set_quota() for quota-based termination; it also terminates respondents who do not
qualify for the quotas.
Example
if not has_xbox:
s.terminate(
"Sorry you don't qualify for this survey "
"because you don't have an Xbox"
)
Parameters
| Name | Type | Description |
|---|---|---|
reason | str | The reason to give to the user to explain why they don't qualify. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
terminate_if
terminate_if(condition: bool, reason: str, number_seconds: int = 0) -> None
Terminate the survey if a condition is met.
Conditionally stops the survey for a respondent.
Condition evaluation
If condition is true, this calls s.terminate(reason) immediately. If it is false,
survey execution continues.
Example
s.terminate_if(
not has_xbox,
"Sorry you don't qualify for this survey because you don't have an Xbox",
)
Parameters
| Name | Type | Description |
|---|---|---|
condition | bool | The condition to check and terminate the user if it's True |
reason | str | The reason to give to the user to explain why they don't qualify. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
complete
complete(
message: str = 'Thank you for completing our survey! See you again.',
number_seconds: int = 0,
) -> None
Complete the survey.
Call this function at the end of the survey to complete the survey and thank the user.
Completion behavior
Use s.terminate() when the respondent should be screened out.
Example
from survey import Survey
s = Survey(**globals())
# Add questions here
s.complete()
Parameters
| Name | Type | Description |
|---|---|---|
message | str | The message to display to the user upon completing the survey. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
rating_question
rating_question(
question: str,
image: MediaItem | None = None,
number_of_points: int | None = None,
style: Literal['slider', 'button', 'star'] = 'slider',
first_point: int | None = None,
labels: dict[int, str] | None = None,
default: int | list[int] | None = None,
recodes: dict[str, str] | None = None,
dont_know_option: str = '',
custom_validator: Callable[[int | str], str | None] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image_size: tuple[int, int] | None = None,
) -> IntResponse
Add a rating-scale question to the survey.
Collect a point on a numeric scale, displayed as a slider, buttons or stars. When the point count is omitted, the scale uses five points or the span of the supplied label keys. Labels may describe only some of the points. A zero point count retains the inferred/default count for compatibility.
Response
Returns an IntResponse containing the selected point. An explicit opt-out returns -999 to
survey code; reporting uses the configured label. Custom validators receive the parsed integer
or opt-out string before post-processing. Recodes map exact point strings to reported labels.
Without a default, simulation samples a scale point and may use the configured opt-out.
Example
from survey import Survey
s = Survey(**globals())
s.rating_question(
"How much do you like this product?",
number_of_points=5,
style="star",
labels={1: "Dislike", 3: "Neutral", 5: "Like"},
dont_know_option="Don't know",
recodes={"1": "dislike", "2": "dislike", "3": "neutral", "4": "like", "5": "like"},
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
image | MediaItem | None | An image to show with the question, from get_image(). |
number_of_points | int | None | The number of points on the scale. If omitted, inferred from labels or defaults to 5. Button and slider styles support up to 11 points; star supports up to 7. |
style | Literal['slider', 'button', 'star'] | the style of the scale, either "slider", "button", or "star" |
first_point | int | None | the first point on the scale (default to 1 or the first label) |
labels | dict[int, str] | None | a dictionary of text labels for each point on the scale |
default | int | list[int] | None | The rating to use during simulation, or a list of candidate ratings. |
recodes | dict[str, str] | None | response mappings to use when reporting this question |
dont_know_option | str | Optionally add a "Don't know" option to the question using this text. |
custom_validator | Callable[[int | str], str | None] | None | function called with the parsed rating; the don't-know option is a string. Return an error message to reject the response, otherwise None. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
net_promoter_score_question
net_promoter_score_question(
question: str,
image: MediaItem | None = None,
number_of_points: int | None = 11,
style: Literal['slider', 'button', 'star'] = 'slider',
first_point: int | None = None,
labels: dict[int, str] | None = None,
default: int | list[int] | None = None,
recodes: dict[str, str] | None = None,
dont_know_option: str = '',
custom_validator: Callable[[int | str], str | None] | None = None,
min_promoter_score: int | None = None,
max_detractor_score: int | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image_size: tuple[int, int] | None = None,
) -> IntResponse
Add a Net Promoter Score question to the survey.
This asks the respondent how likely they are to recommend a product, brand, service, or experience. By default, it uses an 11-point scale from 0 to 10 with endpoint labels for "Not at all likely" and "Extremely likely".
The available styles are "slider", "button", and "star". The scale is numeric and
may include text labels at any point. If labels are omitted, the first and last actual
scale points receive the standard NPS endpoint labels.
Style and scale
first_point defaults to 0 and number_of_points defaults to 11, producing the standard
0-to-10 scale. At least two points are required. A shifted scale runs from first_point
through first_point + number_of_points - 1.
Classified response
The selected raw scale point is classified before it is returned, stored, or reported:
- detractor (
score <= max_detractor_score):IntResponse(-100) - passive (between the thresholds):
IntResponse(0) - promoter (
score >= min_promoter_score):IntResponse(100)
The exact selected point is therefore not retained.
Promoter and detractor scoring
Thresholds are inclusive. Supply min_promoter_score and max_detractor_score together;
each must be a non-boolean integer on the actual scale and the promoter threshold must be
strictly greater than the detractor threshold. Defaults retain the standard relative
positions and shift with first_point: a 0-to-10 scale uses detractor 0-6, passive 7-8,
and promoter 9-10.
Example
from survey import Survey
s = Survey(**globals())
s.net_promoter_score_question(
"How likely are you to recommend this product to a friend or colleague?",
number_of_points=11,
style="slider",
labels={
0: "Not at all likely",
10: "Extremely likely",
},
)
Default and simulated responses
default is a raw point on the displayed scale, but is immediately classified to
-100, 0, or 100. Without a default, simulation selects and classifies a random raw
point.
Recodes
Recodes operate on classified string keys "-100", "0", and "100", not raw score
keys. The configured don't-know label may also be recoded.
from survey import Survey
s = Survey(**globals())
s.net_promoter_score_question(
"How likely are you to recommend this product to a friend or colleague?",
number_of_points=11,
style="slider",
recodes={
"-100": "detractor",
"0": "passive",
"100": "promoter",
},
)
Imported responses
Native imported values -100, 0, and 100 are treated as already-classified buckets so
exports round-trip. Other valid scale points are accepted and classified as raw input. An
imported 0 is therefore the passive bucket, not raw score zero.
Opt-out response contract
When dont_know_option is configured, selecting it stores that label as the parsed response,
passes the string value to custom_validator, and returns -999 to survey code. Reporting
and recoding use the configured label. Empty input remains invalid when no don't-know option
is configured.
Returns
IntResponse: -100 for a detractor, 0 for a passive, 100 for a promoter, or -999
when the configured don't-know option is selected.
Custom validation
custom_validator runs after parsing and classification but before post-processing. Return
a string to reject the response, or None to accept it.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
image | MediaItem | None | An image to show with the question, from get_image(). |
number_of_points | int | None | number of scale points; defaults to 11 and must be between 2 and 11 |
style | Literal['slider', 'button', 'star'] | the style of the scale, either "slider", "button", or "star" |
first_point | int | None | first point on the scale; defaults to 0 or the first supplied label |
labels | dict[int, str] | None | point labels. By default the actual endpoints receive "Not at all likely" and "Extremely likely". |
default | int | list[int] | None | The raw scale point to use during simulation, or a list of candidate scale points. |
recodes | dict[str, str] | None | mappings for classified keys "-100", "0", and "100", plus the optional don't-know label |
dont_know_option | str | Optionally add a "Don't know" option to the question using this text. |
custom_validator | Callable[[int | str], str | None] | None | function called with the classified NPS response; numeric responses are -100, 0, or 100, while don't know is a string. Return an error message to reject it, otherwise None. |
min_promoter_score | int | None | inclusive minimum raw score classified as promoter; supply with max_detractor_score |
max_detractor_score | int | None | inclusive maximum raw score classified as detractor; supply with min_promoter_score |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
ranking_question
ranking_question(
question: str,
options: list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]],
min_options: int | None = None,
max_options: int | None = None,
style: Literal['default', 'button', 'list'] = 'button',
labels: tuple[str, str] = ('Least', 'Most'),
randomize: bool = False,
fixed_options: list[str] | None = None,
other_options: list[str] | None = None,
skip_empty: bool = False,
default: list[str] | list[list[str]] | None = None,
recodes: dict[str, str] | None = None,
custom_validator: Callable[[list[str]], str | None] | None = None,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
dont_know_option: str = '',
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
image: MediaItem | None = None,
) -> ListResponse
Add a ranking question to the survey.
Ask the respondent to rank options in order of preference.
Ranking limits and simulation
Omitted limits use the available option count. For compatibility, zero limits also use that count, and the minimum is clamped to the resolved maximum. An upper bound larger than the available choices remains supported. Every explicit default ranking must respect the resolved limits.
Without a default, simulation returns the displayed options up to the maximum. Their order follows
randomize: it is preserved when false and shuffled when true.
Response
Returns a ListResponse of option strings in ranked order. An explicit opt-out returns a singleton
list containing its label. Recodes affect reported values.
Example
from survey import Survey
s = Survey(**globals())
s.ranking_question(
"Rank these car brands from least to most preferred.",
options=["Ford", "Toyota", "Honda", "Tesla"],
labels=("Least", "Most"),
randomize=True,
default=["Ford", "Toyota", "Honda", "Tesla"],
)
Randomization
Set randomize=True to randomize the order of the options.
fixed_options remain fixed at the end when the other options are randomized.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
options | list[str | MediaItem] | list[str] | list[MediaItem] | dict[str, list[str | MediaItem]] | Options as strings/media. Use a dict to group into subsections, e.g. {'Positive': ['Good', 'Great']}. |
min_options | int | None | the minimum number of options to be ranked, defaults to all options |
max_options | int | None | the maximum number of options to be ranked, defaults to all options |
style | Literal['default', 'button', 'list'] | presentation style for the options. |
labels | tuple[str, str] | a tuple of text labels for the least and most options |
randomize | bool | Whether to randomize the order of the options. |
fixed_options | list[str] | None | Options to keep at the end when the remaining options are randomized. |
other_options | list[str] | None | Additional options to present to the respondent. |
skip_empty | bool | Skip the question when no options are available. |
default | list[str] | list[list[str]] | None | The ranking to use during simulation, or a list of candidate rankings. |
recodes | dict[str, str] | None | Map answers to alternative values in reports. |
custom_validator | Callable[[list[str]], str | None] | None | Function called with the parsed list of selections; return an error message to reject it, otherwise None. |
image_label_field | str | None | The metadata field to use as the label for media items. |
show_image_label | bool | Whether to show each media item's label alongside the image. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
dont_know_option | str | Optionally add a "Don't know" option to the question using this text. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
image | MediaItem | None | An image to show with the question, from get_image(). |
media
@property
media: MaterialCollection
Access the media collection.
This is the original Media material's convenience view.
Use get_material or get_materials for new survey code. Renaming
the original material retains this view; other materials are accessed explicitly.
The media collection contains images and videos that can be used in questions. The media are added to the survey automatically and can be uploaded from the MX8 dashboard. Additional columns added in the dashboard will be added to the media collection.
Each item in the media collection is a MediaItem object. You can access the media collection by iterating over the media object, and pass it to the image parameter of questions.
Columns can be accessed using dot notation. For example, if you have a column called "brand" in your media collection, then you can access it using media.brand. You can also get all the values of a column using the get_media_values function.
If you have not uploaded any media to the survey, then a dummy media collection will be used that contains dummy images with the following columns:
- name
- description
- product
- brand
- campaign
- agency
- id
You can create your own metadata columns in the MX8 dashboard and these will be added to the media collection after you have created the survey and uploaded the media.
The columns are automatically used when reporting the results. For example, if you have a column called "brand" and you ask a question about the brand, then the results will be automatically grouped by brand.
Example
from survey import Survey
s = Survey(**globals())
for media in s.media:
s.select_question("What do you think of this image?",
options=["Like", "Dislike"],
image=media)
get_media_values
get_media_values(column: str, material: str | None = None) -> list[str]
Get all values of the passed metadata column from the media collection.
This is useful if you want to get all the values of a column in the media collection and use them to create questions.
Example
from survey import Survey
s = Survey(**globals())
car_brands = s.get_media_values("brand")
for car in s.media:
s.select_question("What brand is this car?",
options=car_brands,
image=car)
Set material="Products" to read the named material's attachment metadata. Omit it
to retain the original Media convenience view. Use get_materials("Products", column="name")
for column values from both data-only and attachment rows.
Parameters
| Name | Type | Description |
|---|---|---|
column | str | the name of the media metadata column to read from each media item. The column must exist on each media item. |
material | str | None | Optional material name or id; omit for the original Media material. |
get_material
get_material(material: str, /, column: str | None = None, **kwargs: Any) -> MaterialRow | MaterialValue
Read exactly one matching row from a named material.
For example, s.get_material("Products", code="P001") returns a row dictionary.
Set column="name" to read one value from that row. Empty and ambiguous selections
raise a survey validation error. Use s.get_materials(...) for multiple matches,
and s.get_image(...) or s.get_video(...) to fetch an attachment.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | Case-insensitive material name or immutable id. |
column | str | None | Optional column to read from the matching row. |
get_materials
get_materials(material: str, /, column: str | None = None, **kwargs: Any) -> list[MaterialRow] | list[MaterialValue]
Read matching rows from a named material in stored order.
For example, s.get_materials("Products", brand="Acme") returns row dictionaries.
Set column="name" to return values from a declared column. Other keyword arguments
filter exact row values. The material selector is positional-only so a data column
named material can still be filtered. An empty unfiltered material returns an empty
list. Use s.get_images(...) or s.get_videos(...) to fetch attachments.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | Case-insensitive material name or immutable id. |
column | str | None | Optional column to read from the matching rows. |
get_image
get_image(
material: str | None = None,
/,
crop_selection: ImageRectangle | None = None,
**kwargs: Any,
) -> MediaItem
Get the image with the specified values from the media collection.
Media lookup
Keyword arguments other than crop_selection filter the media collection by metadata fields.
Single match
Exactly one image must match. The lookup raises ValueError when no image or more than one
image matches.
Example
from survey import Survey
s = Survey(**globals())
ford_image = s.get_image(brand="Ford")
s.show_image(image=ford_image)
s.complete()
Named materials
An optional first positional argument selects a material by case-insensitive name or
id. For example, s.get_image("Products", brand="Acme") filters that material.
Omit the selector to use the original Media material. This convenience uses the same
native material view and respondent-local tags as get_material/get_materials.
Image crops
Pass crop_selection to return an independent cropped image item. It accepts an
ImageRectangle from an image highlighter response. Coordinates are normalized to the
full source image, with (0, 0) at the top left. The rectangle must fit inside the image.
Omit crop_selection, or pass None, to return the original image.
The crop retains the source filename, security settings and authored metadata. It can be
used in ordinary question images and image options. Image highlighter questions require an
uncropped source image.
The crop is applied before resizing and watermarking; a question's image_size controls the
cropped image's output bounding box. The original collection item is unchanged.
image = s.get_image(name="Advert")
answer = s.image_highlighter_question("Select areas you like.", image=image)
for index, selection in enumerate(answer.rectangles):
cropped = s.get_image(file_name=image.file_name, crop_selection=selection)
s.text_question(
"Why did you choose this area?",
image=cropped,
id="area_follow_up_" + str(index + 1),
tags=s.tag(selection=index + 1),
)
Parameters
| Name | Type | Description |
|---|---|---|
material | str | None | Optional material name or id; omit for the original Media material. |
crop_selection | ImageRectangle | None | Optional normalized rectangle to crop from the image, such as an image highlighter selection. |
get_video
get_video(material: str | None = None, /, **kwargs: Any) -> MediaItem
Get the video with the specified values from the media collection.
Media lookup
Keyword arguments filter the media collection by metadata fields.
Single match
Exactly one video must match. The lookup raises ValueError when no video or more than one
video matches.
Example
from survey import Survey
s = Survey(**globals())
ford_video = s.get_video(brand="Ford")
s.play_video(video=ford_video)
s.complete()
Named materials
An optional first positional argument selects a material by case-insensitive name or
id. For example, s.get_video("Products", brand="Acme") filters that material.
Omit the selector to use the original Media material. This convenience uses the same
native material view and respondent-local tags as get_material/get_materials.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | None | Optional material name or id; omit for the original Media material. |
get_video_thumbnail
get_video_thumbnail(video: MediaItem, offset_seconds: float) -> MediaItem
Get a reusable image of a video at a whole-second position.
The returned item can be used with show_image, question images, or image options.
It inherits the video's metadata, authored description and security settings without changing
the original video. Its file_name and offset_seconds metadata identify the requested frame
in reporting.
A temporary placeholder is shown while a frame is unavailable or still processing.
Fractional offsets are truncated to whole seconds with int(), so section timestamps can be
passed directly. Video extensions are matched case-insensitively.
Example
from survey import Survey
s = Survey(**globals())
video = s.get_video(name="Advert")
frame = s.get_video_thumbnail(video, offset_seconds=12)
s.show_image(frame)
s.text_question("What do you think of this moment?", image=frame)
Response
MediaItem: an independent image item retaining the source video filename and requested offset.
Raises: ValueError: if the source is not a supported video or the offset is nonnumeric, nonfinite, negative or boolean.
Parameters
| Name | Type | Description |
|---|---|---|
video | MediaItem | the source video from the survey media collection. |
offset_seconds | float | a finite non-negative position in seconds, truncated to a whole second. |
get_images
get_images(material: str | None = None, /, **kwargs: Any) -> list[MediaItem]
Get the images with the specified values from the media collection.
Media lookup
Keyword arguments filter the media collection by metadata fields.
Multiple matches
This returns all matching images. The lookup raises ValueError when no image matches.
Example
from survey import Survey
s = Survey(**globals())
for image in s.get_images(brand="Ford"):
s.show_image(image=image)
s.complete()
Named materials
An optional first positional argument selects a material by case-insensitive name or
id. For example, s.get_images("Products", brand="Acme") filters that material.
Omit the selector to use the original Media material. This convenience uses the same
native material view and respondent-local tags as get_material/get_materials.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | None | Optional material name or id; omit for the original Media material. |
get_videos
get_videos(material: str | None = None, /, **kwargs: Any) -> list[MediaItem]
Get the videos with the specified values from the media collection.
Media lookup
Keyword arguments filter the media collection by metadata fields.
Multiple matches
This returns all matching videos. The lookup raises ValueError when no video matches.
Example
from survey import Survey
s = Survey(**globals())
for video in s.get_videos(brand="Ford"):
s.play_video(video=video)
s.complete()
Named materials
An optional first positional argument selects a material by case-insensitive name or
id. For example, s.get_videos("Products", brand="Acme") filters that material.
Omit the selector to use the original Media material. This convenience uses the same
native material view and respondent-local tags as get_material/get_materials.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | None | Optional material name or id; omit for the original Media material. |
store_value
store_value(name: str, value: str | int | bool, tags: dict[str, Any] | None = None) -> StringResponse | BoolResponse | IntResponse
Store a calculated value for reporting.
Use this to add a value calculated from previous answers to the survey data. For survey logic, keep using normal Python variables instead of retrieving stored reporting values.
Reporting
Stored values are added to the survey as calculated variables and can be tagged.
Example
from datetime import datetime
from survey import Survey
s = Survey(**globals())
birth_year = s.numeric_question("What year were you born in?",
min_max=(1920, 2020),
)
age = datetime.now().year - birth_year
s.store_value("age", age)
s.terminate_if(age < 18, "Sorry this survey is for 18+ only.")
Parameters
| Name | Type | Description |
|---|---|---|
name | str | the name of the value to store |
value | str | int | bool | the value to store for reporting |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
store_values
store_values(
name: str,
values: list[str | int | bool],
tags: dict[str, Any] | None = None,
) -> ListResponse
Store multiple calculated values for reporting.
Use this to add a multiselect-style calculated value from previous answers to the survey data. For survey logic, keep using normal Python variables instead of retrieving stored reporting values.
Reporting
Stored values are added to the survey as calculated multi-select variables and can be tagged.
Example
from survey import Survey
s = Survey(**globals())
brands = s.multi_select_question("Which brands do you know?", ["A", "B", "C"])
s.store_values("Known brands bucket", list(brands), tags=s.tag(source="derived"))
Parameters
| Name | Type | Description |
|---|---|---|
name | str | the name of the value to store |
values | list[str | int | bool] | the values to store for reporting |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
time_between
time_between(first_response: BaseResponse, second_response: BaseResponse) -> float | None
Return the elapsed seconds between two responses.
Returns None when timing information is unavailable for either response.
Example
from survey import Survey
s = Survey(**globals())
age = s.numeric_question("How old are you?", min_max=(18, 99))
gender = s.select_question("What is your gender?", options=["Female", "Male", "Non-binary"])
elapsed_seconds = s.time_between(age, gender)
if elapsed_seconds is not None and elapsed_seconds < 1:
s.terminate("You are speeding through the survey.")
random
random() -> float
Return a random float between 0 and 1.
Respondent-stable randomness
Random values are repeatable for the same respondent context.
randomize
randomize(items: Sequence[Any], flatten: bool = False) -> list[Any]
Randomizes a list of items.
Typically used when iterating over a list of items that you want to ask questions about.
Grouped items
Nested lists stay together during top-level randomization, so you can randomize a set of options while keeping grouped options adjacent.
Example
from survey import Survey
s = Survey(**globals())
car_brands = s.randomize(["Ford", "Toyota", "Honda", "Tesla"])
for brand in s.randomize(car_brands):
s.select_question(
"What do you think of {brand} cars?",
options=["Like", "Dislike"],
tags=s.tag(brand=brand),
)
Example with flattening
from survey import Survey
s = Survey(**globals())
genres = [
"Jazz",
["Punk Rock", "Classic Rock", "Indie Rock"], # keep this group together
"Hip-Hop",
["House", "Techno"], # keep this group together
]
all_genres = s.randomize(genres, flatten=True)
for genre in all_genres:
s.select_question(
"What do you think of {genre} music?",
options=["Like", "Dislike", "Neutral"],
tags=s.tag(genre=genre),
)
Parameters
| Name | Type | Description |
|---|---|---|
items | Sequence[Any] | The sequence of items to randomize. |
flatten | bool | If True, flatten any nested lists after randomizing the top-level items. |
conjoint_question
conjoint_question(
question: str,
concepts: list[dict[str, Any]] | list[MediaItem] | list[ConjointConcept] | str | None = None,
task_sets: dict[str, list[list[str]]] | str | None = None,
concept_id_tag: str | None = None,
required_tags: list[str] | None = None,
dont_know_option: str = '',
randomize: bool = False,
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
none_option: str = '',
anchor_question: str | None = None,
anchor_labels: dict[Literal['yes', 'no'] | int, str] | None = None,
concept_labels: list[str] | None = None,
tasks: str | None = None,
) -> DictResponse
Add a choice-based conjoint question to the survey.
Presents one task set as a series of structured conjoint comparison questions.
Named materials
Supply all three references together to join three flat Materials. Each reference accepts a material name or id.
- Concepts has one row per concept. Its designated unique key is the concept id. Other text, number and boolean columns are attributes in declared order. Attachment, security and state columns are excluded from displayed attributes. A concept may own one attachment and recur in any number of tasks.
- Tasks has one row per alternative membership, with its own unique row key and
fixed columns
task_id(text or number),alternative(number) andconcept_id(text or number).concept_idreferences the Concepts key. Alternative positions must be consecutive positive integers starting at 1 within each task. - Task sets has one row per task occurrence, with its own unique row key and fixed
columns
task_set_id(text or number),position(number) andtask_id(text or number).task_idreferences a Tasks group. Positions must be consecutive positive integers starting at 1 within each set. A task can recur in different sets or at different positions in one set.
Attachments belong to Concepts. Missing references, duplicate positions and repeated
concepts within a task fail validation before questions are added. The Concepts key
identifies the selected concept, and its task set and position identify the response.
concept_id_tag, if supplied for named materials, must match the Concepts key.
required_tags controls displayed attributes as for inline concepts.
s.conjoint_question(
"Which product would you choose?",
concepts="Concepts",
tasks="Tasks",
task_sets="Task sets",
)
For inline concepts=[...] and task_sets={...}, omit tasks. The default inline
concept id tag is id.
Task assignment
Each respondent is assigned one task set using least-fill quota behavior.
Response identity
Task responses are keyed by stable task IDs and retain the selected concept's reporting attributes. The response tags also include:
conjoint_task_set,conjoint_task, anddiscrete_choice_task_idto identify the task.conjoint_calibration_method:explicit_noneordirect_response_nonefor calibrated exercises.conjoint_choice_outcome:concept,none, ordont_know.conjoint_direct_anchor:yesornoafter a completed direct-response-none follow-up.
These tags are added automatically. Selecting dont_know_option does not trigger an anchor follow-up.
Dict-backed concepts
Dict-backed concepts render ordered attribute rows without embedding presentation Markdown.
required_tags controls displayed row order when provided. The selected response includes
concept_id_tag and required_tags through option tags.
Set concept_labels=["Product A", "Product B"] to show reusable headings for the
displayed positions in every task. Labels are assigned after option randomization, so
the same concept may receive a different label in another task. At least one label is
required for each position in the widest task. Responses still contain concept ids.
This parameter supports dict-backed concepts only. Without concept_labels, the
existing display is unchanged.
Media-backed concepts
Media-backed concepts use existing media option rendering, labels, descriptions, and media tags.
Explicit none alternative
Set a nonempty none_option to add a completed no-purchase choice beneath the concepts.
The selected response receives conjoint_choice_outcome=none without concept or attribute
topics. An empty string disables the option.
Direct-response-none anchor
Set anchor_question to ask a purchase question after each selected concept.
Use {selected.price}, {selected.brand}, or {selected.field} for any other field
from the selected concept dictionary or media item's tags. For example,
anchor_question="Would you buy {selected.brand} for {selected.price}?" can display
"Would you buy Acme for £20/month?". Use a plain string, not a Python formatted string.
Values are taken from the original concepts, even when the field is omitted from
required_tags. Every concept must supply each referenced field as a string, number,
or boolean; missing fields and unsupported value types fail validation before any
questions are added. Ordinary survey tag placeholders can be used alongside these fields.
Bare {selected} inserts the concept id. Piping values does not redisplay the concept image.
anchor_labels accepts either yes and no keys for a binary purchase question, or integer keys
for a rating question. Binary labels do not change the canonical yes and no values.
Labels must be distinct and nonblank. Rating scales use the same label-span inference as
rating_question, with two to eleven points displayed as buttons. Mixed binary and numeric keys
are rejected. Explicit none and
direct-response-none anchoring are mutually exclusive, and a blank anchor question is
rejected.
For example, first ask which plan the respondent prefers, then whether they would actually buy that plan. The method asks and saves the follow-up automatically:
from survey import Survey
s = Survey(**globals())
choices = s.conjoint_question(
"Which mobile plan would you choose?",
concepts=[
{"id": "Basic", "data": "5 GB", "price": "£10/month"},
{"id": "Plus", "data": "20 GB", "price": "£20/month"},
{"id": "Unlimited", "data": "Unlimited", "price": "£30/month"},
],
task_sets={"plans": [["Basic", "Plus"], ["Plus", "Unlimited"]]},
required_tags=["data", "price"],
anchor_question="Would you buy a plan with {selected.data} for {selected.price}?",
anchor_labels={"yes": "Yes, I would buy it", "no": "No, I would not"},
id="mobile-plans",
)
Each inner list in task_sets is one comparison screen (a "task"). This example
shows two comparisons, each followed by its own purchase question. If the respondent
chooses Plus and then answers No, that task's selected response still contains Plus,
with conjoint_choice_outcome=concept and conjoint_direct_anchor=no. For Plus, the
follow-up reads "Would you buy a plan with 20 GB for £20/month?".
The answer applies to that selection in that task, even if Plus appears again later.
Choosing dont_know_option skips the purchase follow-up.
No separate setter is needed for conjoint. set_maxdiff_direct_anchor is for MaxDiff
item acceptability answers collected separately, as shown in that method's example.
For a purchase-likelihood scale, use integer-keyed labels:
anchor_labels={
1: "Definitely would not buy",
2: "Probably would not buy",
3: "Might or might not buy",
4: "Probably would buy",
5: "Definitely would buy",
}
The selected task response retains its raw numeric answer in conjoint_anchor_rating.
The complete ordered values and labels are retained as JSON text in conjoint_anchor_scale.
The survey does not convert ratings to purchase decisions. Each report selects one inclusive
gte (≥) or lte (≤) cutoff using an actual integer answer value. For example,
{"operator": "gte", "value": 4} counts answers 4 and 5 as purchases on the scale above.
Unanswered follow-ups remain missing.
The question catalogue exposes conjoint_anchor metadata with a rating, yes_no, or
explicit_none type; rating metadata also contains the ordered answers list.
Returned value
The returned DictResponse keeps the existing task-id-to-StringResponse shape. Each
selected task response carries its task identity, calibrated choice outcome, and completed
direct anchor through response topics. A missing follow-up remains missing rather than
changing the original forced concept choice.
Every task response is keyed by its stable discrete_choice_task_id, which has the form
<exercise>:task-set:<task-set>:task:<number>.
Randomization
Set randomize=True to randomize option order within each conjoint task.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
concepts | list[dict[str, Any]] | list[MediaItem] | list[ConjointConcept] | str | None | Concept dictionaries, media items, or the name or id of a Concepts material. |
task_sets | dict[str, list[list[str]]] | str | None | Inline task-set mapping containing concept ids, or the name or id of a Task sets material. |
concept_id_tag | str | None | Concept id tag: id for inline concepts, or the designated key for a Concepts material. |
required_tags | list[str] | None | Concept tags to require and report with selected dict-backed concepts. |
dont_know_option | str | Optional fixed non-concept option label. |
randomize | bool | Whether to randomize option order within each task. |
image_label_field | str | None | Media field to use as the display label for media concepts. |
show_image_label | bool | Whether to show media labels. |
image_size | tuple[int, int] | None | Bounding box size for media options. If omitted, the default rendered size is 600x600. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
none_option | str | Optional fixed explicit-none alternative label. |
anchor_question | str | None | Optional binary or rating purchase question to ask after each selected concept. Use {selected.price} or {selected.field} to insert a concept dictionary value or media tag. Bare {selected} inserts the concept id. |
anchor_labels | dict[Literal['yes', 'no'] | int, str] | None | Display labels keyed by yes and no, or integers for a rating scale. |
concept_labels | list[str] | None | Optional reusable headings for displayed concept positions in each task. |
tasks | str | None | Name or id of the Tasks material when concepts and task_sets name materials. |
max_diff_question
max_diff_question(
question: str,
items: list[str | MediaItem] | list[list[str | MediaItem]],
labels: list[str],
image: MediaItem | None = None,
randomize: bool = False,
custom_validator: Callable[[dict[str, str] | str], str | None] | None = None,
dont_know_option: str = '',
image_label_field: str | None = None,
show_image_label: bool = True,
image_size: tuple[int, int] | None = None,
number_seconds: int = 0,
tags: dict[str, Any] | None = None,
id: str | None = None,
randomize_labels: bool = False,
anchor_question: str | None = None,
anchor_labels: dict[Literal['all', 'some', 'none'], str] | None = None,
) -> DictResponse
Add a MaxDiff question to the survey.
This presents the user with a series of sets of items, and asks the user to select the most and least preferred items in each set.
labels resolves to two distinct values. An empty list retains the default Least/Most labels.
A flat item list uses a bundled design for its item count. Supply nested lists for explicit choice sets.
Randomization
Set randomize=True to randomize item order within each set. Set randomize_labels=True
to randomize the displayed order of the two labels. Within a set, portrait
orientation keeps the same item order for both label questions.
Example
from survey import Survey
s = Survey(**globals())
car_brands = ["Ford", "Toyota", "Honda", "Tesla", "Chevrolet", "BMW", "Audi", "Mercedes"]
s.max_diff_question("Which of the following car brands do you prefer?",
items=car_brands,
labels=["Least", "Most"])
Portrait orientation
Portrait orientation first shows question as an introductory message, then asks one
choice question for each label in every set. The item selected for the first label is
disabled for the second. The method supplies the label-specific follow-up copy, so no
{label} placeholder is required in question.
from survey import Survey
s = Survey(**globals())
car_brands = ["Ford", "Toyota", "Honda", "Tesla", "Chevrolet", "BMW", "Audi", "Mercedes"]
s.max_diff_question("Which of the following cars do you prefer?",
items=car_brands,
labels=["Least", "Most"])
Return value
The returned DictResponse contains every task in generated order, keyed by its stable
discrete_choice_task_id. Each task contains a selections response keyed by the supplied
labels and, when answered, an anchor response containing all, some, or none.
Indirect anchoring
Set anchor_question to ask an all/some/none acceptability question after every MaxDiff
task. anchor_labels can customize the three displayed labels without changing their
all/some/none answer values. An unanswered anchor remains missing.
Direct anchoring: ask about each item separately
Most/least choices tell you which items a respondent prefers relative to the others.
To also find out which items they would actually consider, ask separate acceptability
questions and pass those answers to set_maxdiff_direct_anchor. See that method for
a complete example. One answer applies to an item wherever it appears in this exercise.
This differs from anchor_question, which asks about the whole displayed set after
each comparison and records an all/some/none answer.
from survey import Survey
s = Survey(**globals())
car_brands = s.multi_select_question(
"When you think about cars, which brands immediately come to mind?",
options=["Ford", "Toyota", "Honda", "Tesla"],
)
brand_cars = {
"Ford": ["Fiesta", "Focus", "Mustang", "F150"],
"Toyota": ["Corolla", "Camry", "Prius", "RAV4"],
"Honda": ["Civic", "Accord", "CR-V", "Pilot"],
"Tesla": ["Model S", "Model 3", "Model X", "Model Y"],
}
for brand in car_brands:
s.max_diff_question(
"Which of the following {brand} cars do you prefer?",
items=brand_cars[brand],
labels=["Least", "Most"],
tags=s.tag(brand=brand),
)
Explicit choice sets and custom validation
In landscape, the validator receives a dictionary keyed by the two labels. In portrait it receives
each selected item string. Return an error message to reject the answer, otherwise None.
features = ["Offline access", "Cloud backup", "Team sharing", "Priority support"]
def check_selection(answer: dict[str, str] | str) -> str | None:
selected = answer.values() if isinstance(answer, dict) else [answer]
return "Please reconsider Priority support." if "Priority support" in selected else None
s.max_diff_question(
"Which features matter most and least?",
items=[features],
labels=["Least", "Most"],
custom_validator=check_selection,
)
Parameters
| Name | Type | Description |
|---|---|---|
question | str | The question to ask the respondent. |
items | list[str | MediaItem] | list[list[str | MediaItem]] | items to compare, or predefined sets of items to compare |
labels | list[str] | the two labels to use for the most and least preferred items |
image | MediaItem | None | An image to show with the question, from get_image(). |
randomize | bool | whether to randomize item order within each set |
custom_validator | Callable[[dict[str, str] | str], str | None] | None | function called with the parsed MaxDiff set in landscape orientation or each parsed label choice in portrait orientation; return an error message to reject the response, otherwise None |
dont_know_option | str | label to use for the don't-know option, if any. |
image_label_field | str | None | label field to use for media items in the options. |
show_image_label | bool | whether to show image labels for media options. |
image_size | tuple[int, int] | None | The bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
tags | dict[str, Any] | None | Tags to attach to this question, from s.tag(...). You can also attach tags using the with s.tag(...): context manager. |
id | str | None | Optional stable identifier for this question. If not set the question text is used. |
randomize_labels | bool | whether to randomize the displayed order of the two labels |
anchor_question | str | None | optional all/some/none acceptability question to ask after every task. |
anchor_labels | dict[Literal['all', 'some', 'none'], str] | None | optional display labels keyed by all, some, and none. |
set_maxdiff_direct_anchor
set_maxdiff_direct_anchor(
response: DictResponse,
observations: Mapping[Any, bool | None],
) -> None
Save separately collected acceptability answers against a MaxDiff exercise.
This method saves answers; it does not ask the respondent any questions. First call
max_diff_question, then collect an acceptability answer for each item, then call this
method with the whole MaxDiff response and a dictionary of those answers.
Complete MaxDiff example
Ask which features matter most and least, then whether each feature is something the respondent would actually use:
from survey import Survey
s = Survey(**globals())
features = ["Offline access", "Cloud backup", "Team sharing", "Priority support"]
preferences = s.max_diff_question(
"Which feature matters most and least to you?",
items=[features],
labels=["Least", "Most"],
id="feature-preferences",
)
observations = {}
for feature in features:
answer = s.select_question(
"Would you use {feature}?",
options=["Yes", "No", "Not sure"],
tags=s.tag(feature=feature),
)
observations[feature] = {"Yes": True, "No": False, "Not sure": None}.get(str(answer))
s.set_maxdiff_direct_anchor(preferences, observations=observations)
items=[features] supplies one comparison containing all four items. For multiple
predefined comparisons, supply multiple inner lists. Include each distinct item from
all those lists exactly once in observations, including items never picked as most
or least. For media items, use str(item) as the dictionary key; string items use
their original text. Do not use task ids, selection labels, or translated display text.
What the answers mean
Each dictionary entry answers "is this item acceptable to this respondent?":
Truemeans the item is acceptable.Falsemeans the item is unacceptable.Nonemeans the answer is unknown or was not given.
Include a key with None when the answer is unknown; leaving the key out is an error.
Pass actual booleans or None, not strings such as "Yes" or numbers such as 1.
One answer applies to every most/least selection of that item across this exercise.
Items never selected do not create direct-anchor reporting observations. The separate
acceptability questions retain their own answers in the usual way.
Call this after the questions that collect the answers.
Repeating the same mapping is safe. Changing it after it has been saved, supplying an
unknown or missing item, or using an invalid value raises SurveyValidationError.
Conjoint uses a built-in follow-up
For conjoint, pass anchor_question and optionally anchor_labels to
conjoint_question. It asks a yes/no purchase question after each selected concept and
saves conjoint_direct_anchor=yes or no automatically. See conjoint_question for
a complete example. Do not pass a conjoint response to this method.
Parameters
| Name | Type | Description |
|---|---|---|
response | DictResponse | Whole DictResponse returned by max_diff_question, not one task or selection. |
observations | Mapping[Any, bool | None] | Dictionary mapping every distinct item to True (acceptable), False (unacceptable), or None (unknown). Media item keys use str(item). |
count_validation_errors
count_validation_errors(question: str | None = None) -> int
Return the number of validation errors in the survey, or for a specific question.
Scope
If question is omitted or empty, this counts all current respondent validation warning
entries. If question is provided, warnings for every question with that exact text are
counted; a known question with no active warning returns zero.
Raises
KeyError if a nonempty question text does not match any survey element.
Parameters
| Name | Type | Description |
|---|---|---|
question | str | None | If nonempty, only count validation errors for questions with this exact text. |
authenticate_by_phone_number
authenticate_by_phone_number(
question_1: str,
question_2: str = 'Please enter the code we sent you.',
termination_message: str = 'Sorry, the code you entered was incorrect',
store_phone_number: bool = False,
image: MediaItem | None = None,
default_country: str | None = None,
number_seconds: int = 0,
id: str | None = None,
image_size: tuple[int, int] | None = None,
) -> StringResponse
Authenticate the respondent by phone number.
Ask for a phone number, send a verification code, and require the respondent to enter the code before continuing. An incorrect code terminates the survey.
Response
Returns a StringResponse with phone_number and otp attributes. store_phone_number controls
the response text: when false it is "obfuscated". The actual number remains available through
response.phone_number.
Example
from survey import Survey
s = Survey(**globals())
s.authenticate_by_phone_number(
"Enter your phone number to continue. We will send you a verification code.",
default_country="GB",
)
Parameters
| Name | Type | Description |
|---|---|---|
question_1 | str | the question that asks the respondent to enter their phone number |
question_2 | str | the question that asks the respondent to enter the verification code |
termination_message | str | the message to show the respondent if the code is incorrect |
store_phone_number | bool | whether to include the phone number in response text; the raw phone_number attribute remains available |
image | MediaItem | None | An image from get_image() for the phone number question. |
default_country | str | None | the default country code to use for the phone number |
number_seconds | int | Seconds to wait before allowing the respondent to continue. |
id | str | None | Optional stable identifier prefix for this question. If not set the question text is used. |
image_size | tuple[int, int] | None | the bounding box size of the image to display. If omitted, the default rendered size is 600x600. |
call_api
call_api(
url: str,
method: Literal['get', 'post', 'GET', 'POST'],
data: dict[Any, Any] | None = None,
params: dict[Any, Any] | None = None,
headers: dict[Any, Any] | None = None,
timeout: int = 10,
) -> StringResponse
Call an external API on an allowlisted domain.
Allowed domains
External API calls are only available for pre-approved domains.
Request payloads
method accepts GET or POST, case-insensitively. Use params for GET query parameters and
data for POST request bodies. Any {respondent_id} placeholder in url is replaced with
the current respondent ID before the request is created.
Return value and simulation
A live call returns the response body as a StringResponse. Simulation and other
machine-generated runs skip the network request and return an empty StringResponse.
Timeout and errors
Only HTTP status 200 is accepted. A disallowed domain or any other response status raises
SurveyValidationError.
Returns
StringResponse: response body text, or an empty response during simulation.
Raises
SurveyValidationError if the domain is not allowlisted or the response status is not 200.
Parameters
| Name | Type | Description |
|---|---|---|
url | str | URL on an allowlisted domain. May contain {respondent_id}. |
method | Literal['get', 'post', 'GET', 'POST'] | request method, either GET or POST. |
data | dict[Any, Any] | None | form data to send in the POST request body. |
params | dict[Any, Any] | None | query parameters to include in the request. |
headers | dict[Any, Any] | None | HTTP headers to include in the request. |
timeout | int | request timeout in seconds. |
get_all_children_age_gender
get_all_children_age_gender(
min_age: int,
max_age: int,
age_recodes: dict[int, str] | None = None,
gender_map: dict[str, str] | None = None,
question_1_text: str | None = None,
question_2_text: str | None = None,
question_3_text: str | None = None,
id: str | None = None,
) -> list[StringResponse]
Ask the user a series of questions to get the ages and genders of their children.
Returns a list of StringResponse objects, one for each child, with the following tags attached:
- age: the recoded age of the child
- gender: the gender of the child
- name: the name of the child to present to the respondent, e.g. 16 year old son.
Responses retain grid order. Children with the same age and gender remain separate entries.
No children
If the user has no children, an empty list is returned.
Default question sequence
The default questions are:
- "How many children do you have between the ages of {min_age} and {max_age}?"
- "For each child, please let us know their age"
- "Now, please let us know their gender"
Example usage
from survey import Survey
s = Survey(**globals())
children = s.get_all_children_age_gender(
min_age=5,
max_age=18,
)
for child in children:
s.text_question(
"Thinking about {child}, what is their favorite subject in school?",
tags=s.tag(child=child.name),
)
s.complete()
Parameters
| Name | Type | Description |
|---|---|---|
min_age | int | the minimum age of the children |
max_age | int | the maximum age of the children |
age_recodes | dict[int, str] | None | Map ages to reporting labels, such as {5: 'Primary'}. Unmapped ages keep their numeric value. |
gender_map | dict[str, str] | None | Map gender answers to child names. Defaults to Male → son and Female → daughter. |
question_1_text | str | None | The question asking how many children fall within the age range. |
question_2_text | str | None | The question asking the age of each child. |
question_3_text | str | None | The question asking the gender of each child. |
id | str | None | Optional stable identifier prefix for generated child questions. If not set the question text is used. |
kid_picker_question
kid_picker_question(
min_age: int = 13,
max_age: int = 17,
age_recodes: dict[int, str] | None = None,
gender_map: dict[str, str] | None = None,
question_1_text: str | None = None,
question_2_text: str | None = None,
question_3_text: str | None = None,
question_4_text: str | None = None,
id: str | None = None,
) -> StringResponse | None
Ask for child age and gender, then select the child available to take the survey.
This asks a series of questions to collect eligible children and then asks which child is available.
Returns the selected child as a StringResponse with age, gender, and name attributes.
Return shape and tags
The returned child can be used directly in survey logic and tags. The response value is the raw age
and gender, child.age is the recoded age if age_recodes is provided, child.gender is the raw
gender response, and child.name is the respondent-facing child label. These age, gender, and
name values are response tags. Children with the same name are numbered only in the availability
options so each child remains separately selectable.
When a child is selected, the helper also stores reportable calculated fields named
Selected child age and Selected child gender.
No children
None is returned when the respondent has no eligible children or selects the fixed None
option at the availability question.
Default question sequence
Collects child count, ages, and genders using get_all_children_age_gender, then asks
which child is available to take the survey now.
Example usage
from survey import Survey
s = Survey(**globals())
child = s.kid_picker_question(
min_age=5,
max_age=18,
)
if child:
s.show_message(
"Please ask your {child} to take the survey now.",
tags=s.tag(
child=child.name,
selected_child_age=child.age,
selected_child_gender=child.gender,
),
)
else:
s.terminate("Sorry, this survey is for children only.")
s.complete()
Parameters
| Name | Type | Description |
|---|---|---|
min_age | int | the minimum age of the children |
max_age | int | the maximum age of the children |
age_recodes | dict[int, str] | None | Map ages to reporting labels, such as {5: 'Primary'}. Unmapped ages keep their numeric value. |
gender_map | dict[str, str] | None | Map gender answers to child names. Defaults to Male → son and Female → daughter. |
question_1_text | str | None | The question asking how many children fall within the age range. |
question_2_text | str | None | The question asking the age of each child. |
question_3_text | str | None | The question asking the gender of each child. |
question_4_text | str | None | The question asking which child is available to take the survey now. |
id | str | None | Optional stable identifier prefix for generated child picker questions. If not set the question text is used. |
get_exposures
get_exposures(source: str, id: str | None = None) -> ListResponse
Return tagged exposure records for reporting and branching.
Each record reports every dimension returned by the exposure service as a response topic.
It also reports frequency, exposure_source, and, when available, days_since_exposure.
Use the topic attributes to branch on combinations without losing their relationship.
Pre-loaded exposure records
The exposure service must return linked records under records, where each record has a
dimensions mapping plus its exposures count. For example, a record can carry both
campaign and creative dimensions. The older dimension-aggregate payload is not used
by this method because it does not retain those links.
Example
from survey import Survey
s = Survey(**globals())
exposures = s.get_exposures(source="campaign-123", id="ad-exposures")
if any(exposure.campaign == "campaign-a" and exposure.creative == "creative-b" for exposure in exposures):
s.select_question("What did you think of this advert?", options=["Like", "Dislike"])
s.complete()
Parameters
| Name | Type | Description |
|---|---|---|
source | str | the source of the exposures, set with the server side integration, e.g. 'campaign-123' |
id | str | None | an optional reporting ID for the exposure records. |
tag_exposed_materials
tag_exposed_materials(
material: str,
/,
source: str,
field_name: str,
exposed_dimension: str = 'brand',
number_allowed_unknown_values: int = 0,
) -> None
Tag named material rows using the respondent's pre-loaded exposure data.
The supplied material field is matched against values from source and
exposed_dimension. Rows receive exposed=True or False; exposed rows also receive
frequency and, when available, days_since_exposure. Tags are shared by row and
attachment accessors during this execution and never written to the stored survey.
Reapplying exposure tags removes stale frequency/recency from unexposed rows.
s.tag_exposed_materials("Products", source="campaign-123", field_name="brand")
for image in s.get_images("Products", exposed=True):
s.show_image(image)
number_allowed_unknown_values retains the existing allow-list policy. Exposure
records must be loaded for the respondent's IP address before using this method.
Parameters
| Name | Type | Description |
|---|---|---|
material | str | Material name or id to tag. |
source | str | The source of pre-loaded exposure data, for example campaign-123. |
field_name | str | Material column matched against exposure values. |
exposed_dimension | str | Exposure dimension to match. |
number_allowed_unknown_values | int | Number of values outside the material allow-list that may be accepted. |
tag_exposed_media
tag_exposed_media(
source: str,
field_name: str,
exposed_dimension: str = 'brand',
number_allowed_unknown_values: int | None = None,
number_allowed_unknown_brands: int | None = None,
) -> None
Use tag_exposed_materials("Material name", ...) for new survey scripts.
This deprecated method targets the original Media material, including its
placeholder items. Existing source,
field_name, exposed_dimension, and threshold arguments retain their meaning.
number_allowed_unknown_brands remains a deprecated alias for
number_allowed_unknown_values. Supply at most one threshold argument.
Parameters
| Name | Type | Description |
|---|---|---|
source | str | the source of the exposures, set with the server side integration, e.g. 'campaign-123' |
field_name | str | the name of the field in the media collection to match against the exposures |
exposed_dimension | str | the exposure dimension to match against, defaults to 'brand' |
number_allowed_unknown_values | int | None | the number of values that are not in the allow-list that are allowed before the lookup is failed |
number_allowed_unknown_brands | int | None | deprecated alias for number_allowed_unknown_values |
insert_block
insert_block(name: str) -> None
Insert a block into the survey at the current position.
Blocks are defined in the MX8 dashboard and can be used to add custom questions to surveys without modifying the survey code.
Dashboard-defined blocks
The block name must refer to a block configured in the MX8 dashboard.
Missing blocks
If the named block is unavailable, block insertion fails during survey processing.
Parameters
| Name | Type | Description |
|---|---|---|
name | str | the name of the block |
