From eb239b6dac8983af9b4169332b6312aeba2c5f7b Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Tue, 5 Feb 2013 10:58:40 -0500 Subject: [PATCH] Add question class storage (lookups in QUESTION_CLASS) This allows us to specify questions with alternate processing classes. As a simple example, I've added NormalizedStringQuestion, which softens the string comparison used in the basic Question. The next step is to add a command-line question ;). --- quiz.json | 3 ++- quizzer/question.py | 27 +++++++++++++++++++++++++++ quizzer/quiz.py | 10 ++++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/quiz.json b/quiz.json index 1789fd6..9677dba 100644 --- a/quiz.json +++ b/quiz.json @@ -15,8 +15,9 @@ ] }, { + "class": "NormalizedStringQuestion", "prompt": "What is your favourite color?", - "answer": "Blue", + "answer": "blue", "hint": "Channel Sir Lancelot", "dependencies": [ "What is your quest?" diff --git a/quizzer/question.py b/quizzer/question.py index e423adf..10ae4fd 100644 --- a/quizzer/question.py +++ b/quizzer/question.py @@ -1,3 +1,10 @@ +QUESTION_CLASS = {} + + +def register_question(question_class): + QUESTION_CLASS[question_class.__name__] = question_class + + class Question (object): def __init__(self, id=None, prompt=None, answer=None, help=None, dependencies=None): @@ -36,3 +43,23 @@ class Question (object): def check(self, answer): return answer == self.answer + + +class NormalizedStringQuestion (Question): + def normalize(self, string): + return string.strip().lower() + + def check(self, answer): + return self.normalize(answer) == self.normalize(self.answer) + + +for name,obj in list(locals().items()): + if name.startswith('_'): + continue + try: + subclass = issubclass(obj, Question) + except TypeError: # obj is not a class + continue + if subclass: + register_question(obj) +del name, obj diff --git a/quizzer/quiz.py b/quizzer/quiz.py index c3fa5a5..7c49e94 100644 --- a/quizzer/quiz.py +++ b/quizzer/quiz.py @@ -28,14 +28,20 @@ class Quiz (list): raise NotImplementedError('upgrade from {} to {}'.format( version, __version__)) for state in data['questions']: - q = _question.Question() + question_class_name = state.pop('class', 'Question') + question_class = _question.QUESTION_CLASS[question_class_name] + q = question_class() q.__setstate__(state) self.append(q) def save(self, **kwargs): + questions = [] + for question in self: + state = question.__getstate__() + state['class'] = type(question).__name__ data = { 'version': __version__, - 'questions': [question.__getstate__() for question in self], + 'questions': questions, } with self._open(mode='w', **kwargs) as f: _json.dump( -- 2.26.2