aboutsummaryrefslogtreecommitdiff
path: root/ch1p/state.py
blob: e7fe050f41e071a23b65ca0734bb7213a3fbc310 (plain)
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
import os, json

from .functions import _get_vars


class State:
    def __init__(self, default=None, **kwargs):
        file, = _get_vars([
            ('file', 'STATE_FILE')
        ], kwargs)

        if default is None:
            default = {}

        self.file = file
        self.default = default

    def read(self) -> dict:
        if not os.path.exists(self.file):
            self.write(self.default)
            return self.default

        with open(self.file, 'r') as f:
            return json.loads(f.read())

    def write(self, state: dict):
        with open(self.file, 'w') as f:
            f.write(json.dumps(state))