# 1. load from data storage
class ConsistentContext:
  def __init__(self, filename):
    self.filename = filename
    self._load()
  def _load(self):
    try:
      with open(self.filename, 'rt') as file:
        self.data = [eval(line) for line in file]
    except:
      print(f'making {self.filename} new')
      self.data = []
      self.save()
  def save(self):
    with open(self.filename + '.tmp', 'rt') as file:
      for idx, line in enumerate(self.data):
        if idx > 0:
          file.write('\n')
        file.write(repr(line))
  def __del__(self):
    self.save()

Reply via email to