Add `# Copyright` tags to Python files
[quizzer.git] / quizzer / answerdb.py
1 # Copyright
2
3 import codecs as _codecs
4 import json as _json
5
6 from . import __version__
7
8
9 class AnswerDatabase (dict):
10     def __init__(self, path=None, encoding=None):
11         super(AnswerDatabase, self).__init__()
12         self.path = path
13         self.encoding = encoding
14
15     def _open(self, mode='r', path=None, encoding=None):
16         if path:
17             self.path = path
18         if encoding:
19             self.encoding = encoding
20         return _codecs.open(self.path, mode, self.encoding)
21
22     def load(self, **kwargs):
23         with self._open(mode='r', **kwargs) as f:
24             data = _json.load(f)
25         version = data.get('version', None)
26         if version != __version__:
27             raise NotImplementedError('upgrade from {} to {}'.format(
28                     version, __version__))
29         self.update(data['answers'])
30
31     def save(self, **kwargs):
32         data = {
33             'version': __version__,
34             'answers': self,
35             }
36         with self._open(mode='w', **kwargs) as f:
37             _json.dump(
38                 data, f, indent=2, separators=(',', ': '), sort_keys=True)
39             f.write('\n')
40
41     def add(self, question, answer, correct):
42         if question.id not in self:
43             self[question.id] = []
44         self[question.id].append({
45                 'answer': answer,
46                 'correct': correct,
47                 })
48
49     def get_answered(self, questions):
50         return [q for q in questions if q.id in self]
51
52     def get_unanswered(self, questions):
53         return [q for q in questions if q.id not in self]
54
55     def get_correctly_answered(self, questions):
56         return [q for q in questions
57                 if True in [a['correct'] for a in self.get(q.id, [])]]
58
59     def get_never_correctly_answered(self, questions):
60         return [q for q in questions
61                 if True not in [a['correct'] for a in self.get(q.id, [])]]