|
| 1 | +import types |
| 2 | + |
| 3 | + |
| 4 | +class MicroEnv: |
| 5 | + def __init__(self, obj, descriptor) -> None: |
| 6 | + self.descriptor = descriptor |
| 7 | + self.id = descriptor["id"] |
| 8 | + self.face = obj |
| 9 | + self.data = {} |
| 10 | + self.supply_demand(obj, descriptor) |
| 11 | + |
| 12 | + def create_scoped_demand(self, root_props, props, suppliers={}) -> object: |
| 13 | + demand_key = props[1]["id"] |
| 14 | + path = f"{root_props['path']}/{demand_key}" |
| 15 | + self.data[path] = { |
| 16 | + "key": demand_key, |
| 17 | + "type": "chidlren", |
| 18 | + "path": path, |
| 19 | + "data": props[0], |
| 20 | + "suppliers": suppliers, |
| 21 | + } |
| 22 | + return self.data[path] |
| 23 | + |
| 24 | + def global_demand(self, props) -> object: |
| 25 | + key = props["key"] |
| 26 | + _type = props["type"] |
| 27 | + path = props["path"] |
| 28 | + |
| 29 | + if not key or not _type or not path: |
| 30 | + raise ValueError("Key, Type, and Path are required in global_demand.") |
| 31 | + |
| 32 | + if "children" in self.descriptor: |
| 33 | + self.create_scoped_demand( |
| 34 | + props, self.descriptor["children"] |
| 35 | + ) |
| 36 | + |
| 37 | + return props |
| 38 | + |
| 39 | + def supply_demand(self, obj, descriptor, suppliers={}) -> object: |
| 40 | + data = descriptor.copy() |
| 41 | + data["$$root"] = obj |
| 42 | + self.data["root"] = { |
| 43 | + "key": "root", |
| 44 | + "type": "$$root", |
| 45 | + "path": "root", |
| 46 | + "data": obj, |
| 47 | + "suppliers": suppliers, |
| 48 | + } |
| 49 | + self.global_demand(self.data["root"]) |
| 50 | + |
| 51 | + def get(self, key, path="root") -> any: |
| 52 | + if isinstance(self.data[path]["data"][key], types.FunctionType): |
| 53 | + return self.data[path]["data"][key]() |
| 54 | + else: |
| 55 | + return self.data[path]["data"][key] |
| 56 | + |
| 57 | + def set(self, key, value, path="root") -> any: |
| 58 | + self.data[path]["data"][key] = value |
| 59 | + return self.data[path]["data"][key] |
0 commit comments