Skip to content

Questions

Utilities for dealing with questions.

from prairielearn import ...

PartialScore

A class with type signatures for the partial scores dict.

For more information see the element developer guide.

QuestionData

A class with type signatures for the data dictionary.

For more information see the element developer guide.

add_files_format_error

add_files_format_error(
    data: QuestionData, error: str
) -> None

Add a format error to the data dictionary.

Examples:

>>> add_files_format_error(data, f"Missing baz in foo.txt")
>>> data["format_errors"]
{"_files": ["Missing baz in foo.txt"]}

add_submitted_file

add_submitted_file(
    data: QuestionData,
    file_name: str,
    base64_contents: str,
    *,
    mimetype: str | None = None,
) -> None

Add a submitted file to the data dictionary.

Examples:

>>> add_submitted_file(data, "foo.txt", "base64-contents", mimetype="text/plain")
>>> data["submitted_answers"]
{"_files": [{"name": "foo.txt", "contents": "base64-contents", "mimetype": "text/plain"}]}

all_partial_scores_correct

all_partial_scores_correct(data: QuestionData) -> bool

Check if all partial scores are close to 1.

Returns:

Type Description
bool

True if all scores are close to 1 and not an empty list, False otherwise.

Examples:

>>> data = {"partial_scores": {"foo":{"score": 1.0}}}
>>> all_partial_scores_correct(data)
True
>>> data = {"partial_scores": {"foo": {"score": 1.0}, "bar": {"score": 0.5}}}
>>> all_partial_scores_correct(data)
False

set_all_or_nothing_score_data

set_all_or_nothing_score_data(data: QuestionData) -> None

Give points to main question score if all partial scores are correct.

Examples:

>>> data = {"partial_scores": {"foo": {"score": 1.0}, "bar": {"score": 1.0}}}
>>> set_all_or_nothing_score_data(data)
>>> data["score"]
1.0
>>> data = {"partial_scores": {"foo": {"score": 1.0}, "bar": {"score": 0.5}}}
>>> set_all_or_nothing_score_data(data)
>>> data["score"]
0.0

set_weighted_score_data

set_weighted_score_data(
    data: QuestionData, weight_default: int = 1
) -> None

Set overall question score to be weighted average of all partial scores. Use weight_default to fill in a default weight for a score if one is missing.

Raises:

Type Description
ValueError

If any of the partial scores have a score of None.

Examples:

>>> data = {
...     "partial_scores": {
...         "foo": {"score": 0.5, "weight": 1},
...         "bar": {"score": 0.8, "weight": 2}
...     }
... }
>>> set_weighted_score_data(data)
>>> data["score"]
0.7