Compare new information with the existing one and update if differs. :param value: the value stored :param section: the primary key of the information :param sub_section: the secondary key of the information :returns: a tuple where the first value is if it differs a
(
self,
value: Any,
section: str,
sub_section: str | None = None,
)
| 32 | |
| 33 | @contextmanager |
| 34 | def compare( |
| 35 | self, |
| 36 | value: Any, |
| 37 | section: str, |
| 38 | sub_section: str | None = None, |
| 39 | ) -> Iterator[tuple[bool, Any | None]]: |
| 40 | """Compare new information with the existing one and update if differs. |
| 41 | |
| 42 | :param value: the value stored |
| 43 | :param section: the primary key of the information |
| 44 | :param sub_section: the secondary key of the information |
| 45 | |
| 46 | :returns: a tuple where the first value is if it differs and the second is the old value |
| 47 | |
| 48 | """ |
| 49 | old = self._content.get(section) |
| 50 | if sub_section is not None and old is not None: |
| 51 | old = old.get(sub_section) |
| 52 | |
| 53 | if old == value: |
| 54 | yield True, old |
| 55 | else: |
| 56 | raised = True |
| 57 | try: |
| 58 | yield False, old |
| 59 | raised = False |
| 60 | finally: |
| 61 | if not raised: # only update when the body did not raise |
| 62 | if sub_section is None: |
| 63 | self._content[section] = value |
| 64 | elif self._content.get(section) is None: |
| 65 | self._content[section] = {sub_section: value} |
| 66 | else: |
| 67 | self._content[section][sub_section] = value |
| 68 | self._write() |
| 69 | |
| 70 | def reset(self) -> None: |
| 71 | self._content = {} |