[e988c2]: / scripts / generate_quiz_from_answers.py

Download this file

78 lines (63 with data), 2.2 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
"""
Reads a Python file defining a set of quiz questions and write an empty quiz ready to be
filled with answers to stdout
"""
import argparse
import importlib.util
import textwrap
from pathlib import Path
from ehrql.utils.string_utils import strip_indent
def main(quiz_answer_file):
quiz = load_module(quiz_answer_file)
introduction = quiz.introduction
imports = get_imports(quiz_answer_file)
questions = "\n\n".join(get_question_text(q) for q in quiz.questions.get_all())
contents = (
f"{as_comment(introduction)}\n"
f"\n"
f"from {quiz_answer_file.stem} import questions\n"
f"\n"
f"{imports}\n"
f"\n"
f"\n"
f"{questions}\n"
f"\n"
f"questions.summarise()"
)
print(contents)
def load_module(module_path):
# Taken from the official recipe for importing a module from a file path:
# https://docs.python.org/3.9/library/importlib.html#importing-a-source-file-directly
spec = importlib.util.spec_from_file_location(module_path.stem, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def get_imports(module_path):
imports = []
for line in module_path.read_text().splitlines():
if not line or line.startswith("#"):
continue
# Skip imports related to the quiz mechanics itself
if "ehrql.quiz" in line:
continue
# We take the line defining the introduction as marking the end of the imports
if "introduction" in line:
break
imports.append(line)
return "\n".join(imports)
def get_question_text(question):
return "\n".join(
[
f"# Question {question.index}",
as_comment(question.prompt),
f"questions[{question.index}].check(...)",
]
)
def as_comment(text):
return textwrap.indent(strip_indent(text), "# ")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("quiz_answer_file", type=Path)
kwargs = vars(parser.parse_args())
main(**kwargs)