Last active
January 25, 2019 20:52
-
-
Save ostcar/b81cb3c0b25b9ab60555b6cf42d0e3bc to your computer and use it in GitHub Desktop.
Example for an all_data_dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import UserDict | |
from typing import Any, Dict, Generator, Tuple, Union | |
ElementID = Tuple[str, int] | |
Element = Dict[str, Any] | |
CollectionType = Union[Dict[int, Element], "Collection"] | |
class AllData(UserDict): | |
def __init__(self, initialdata: Dict[str, CollectionType]) -> None: | |
for name, collection in initialdata.items(): | |
if isinstance(collection, dict): | |
initialdata[name] = Collection(collection) | |
super().__init__(initialdata) | |
def get_changed_elements(self) -> Generator[ElementID, None, None]: | |
for name, collection in self.items(): | |
for id in collection.get_changed_elements(): | |
yield (name, id) | |
class Collection(UserDict): | |
data: Dict[int, Element] | |
name: str | |
changed: bool = False | |
init_hashes: Dict[int, int] | |
def __init__(self, initialdata: Dict[int, Element]) -> None: | |
self.init_hashes = {} | |
for id, element in initialdata.items(): | |
self.init_hashes[id] = hash(repr(element)) | |
super().__init__(initialdata) | |
def add_element(self, element: Element) -> None: | |
new_id = max(self) + 1 | |
element["id"] = new_id | |
self[new_id] = element | |
def get_changed_elements(self) -> Generator[int, None, None]: | |
for id, element in self.items(): | |
if hash(repr(element)) != self.init_hashes.get(id): | |
yield id | |
def test(): | |
all_data = AllData( | |
{ | |
"core/config": { | |
1: {"id": 1, "key": "myconfig", "value": "some value"}, | |
2: {"id": 2, "key": "otherconfig", "value": "some other value"}, | |
}, | |
"assignments/assignment": { | |
1: { | |
"id": 1, | |
"title": "IT-Guy", | |
"polls": [{"id": 1, "yes": 50, "no": 30}], | |
} | |
}, | |
} | |
) | |
my_assignment = all_data["assignments/assignment"][1] | |
my_assignment["polls"].append({"id": 2, "yes": 10, "no": 20}) | |
assert ("assignments/assignment", 1) in all_data.get_changed_elements() | |
all_data["core/config"][1]["value"] = "changed value" | |
assert ("core/config", 1) in all_data.get_changed_elements() | |
all_data["assignments/assignment"].add_element( | |
{"title": "new assignment", "polls": []} | |
) | |
assignment = all_data["assignments/assignment"][2] | |
assert assignment["title"] == "new assignment" | |
assert assignment["id"] == 2 | |
assert ("assignments/assignment", 2) in all_data.get_changed_elements() | |
if __name__ == "__main__": | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment