|
| 1 | +import re |
| 2 | + |
| 3 | + |
| 4 | +class NestedParser: |
| 5 | + _valid = None |
| 6 | + errors = None |
| 7 | + _reg = re.compile(r"\[|\]") |
| 8 | + |
| 9 | + def __init__(self, data): |
| 10 | + self.data = data |
| 11 | + |
| 12 | + def split_key(self, key): |
| 13 | + # remove space |
| 14 | + k = key.replace(" ", "") |
| 15 | + # remove empty string and count key length for check is a good format |
| 16 | + # reduce + filter are a hight cost so do manualy with for loop |
| 17 | + results = [] |
| 18 | + check = -2 |
| 19 | + |
| 20 | + for select in self._reg.split(k): |
| 21 | + if select: |
| 22 | + results.append(select) |
| 23 | + check += len(select) + 2 |
| 24 | + |
| 25 | + if len(k) != check: |
| 26 | + raise Exception(f"invalid format from key {key}") |
| 27 | + return results |
| 28 | + |
| 29 | + def set_type(self, dtc, key, value, full_keys): |
| 30 | + if key.isdigit(): |
| 31 | + key = int(key) |
| 32 | + if len(dtc) < key: |
| 33 | + raise Exception( |
| 34 | + f"key \"{full_keys}\" is upper than actual list") |
| 35 | + if len(dtc) == key: |
| 36 | + dtc.append(value) |
| 37 | + return key |
| 38 | + elif key not in dtc: |
| 39 | + dtc[key] = value |
| 40 | + return key |
| 41 | + |
| 42 | + def construct(self, data): |
| 43 | + dictionary = {} |
| 44 | + |
| 45 | + for key in data: |
| 46 | + keys = self.split_key(key) |
| 47 | + tmp = dictionary |
| 48 | + |
| 49 | + # optimize with while loop instend of for in with zip function |
| 50 | + i = 0 |
| 51 | + lenght = len(keys) - 1 |
| 52 | + while i < lenght: |
| 53 | + set_type = [] if keys[i+1].isdigit() else {} |
| 54 | + tmp = tmp[self.set_type(tmp, keys[i], set_type, key)] |
| 55 | + i += 1 |
| 56 | + |
| 57 | + self.set_type(tmp, keys[-1], data[key], key) |
| 58 | + return dictionary |
| 59 | + |
| 60 | + def is_valid(self): |
| 61 | + self._valid = False |
| 62 | + try: |
| 63 | + self.__validate_data = self.construct(self.data) |
| 64 | + self._valid = True |
| 65 | + except Exception as err: |
| 66 | + self.errors = err |
| 67 | + return self._valid |
| 68 | + |
| 69 | + @property |
| 70 | + def validate_data(self): |
| 71 | + if self._valid is None: |
| 72 | + raise ValueError( |
| 73 | + "You need to be call is_valid() before access validate_data") |
| 74 | + if self._valid is False: |
| 75 | + raise ValueError("You can't get validate data") |
| 76 | + return self.__validate_data |
0 commit comments