| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | 26 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 27 | self.nodes = [] |
| 28 | self.edges = [] |
| 29 | self.attrs = {} |
| 30 | |
| 31 | # Edge Case: Handle None input |
| 32 | if data is None: |
| 33 | return |
| 34 | |
| 35 | # Edge Case: Handle non-list input |
| 36 | if not isinstance(data, list): |
| 37 | raise TypeError("Graph data malformed") |
| 38 | |
| 39 | # Edge Case: Handle empty list |
| 40 | if len(data) == 0: |
| 41 | return |
| 42 | |
| 43 | for item in data: |
| 44 | # Edge Case: Handle non-tuple items |
| 45 | if not isinstance(item, tuple): |
| 46 | raise TypeError("Graph item malformed") |
| 47 | |
| 48 | # Edge Case: Handle empty tuples |
| 49 | if len(item) == 0: |
| 50 | raise TypeError("Graph item malformed") |
| 51 | |
| 52 | item_type = item[0] |
| 53 | |
| 54 | # Edge Case: Handle unknown item types |
| 55 | if item_type not in [NODE, EDGE, ATTR]: |
| 56 | raise ValueError("Unknown item") |
| 57 | |
| 58 | # Edge Case: Handle ATTR items |
| 59 | if item_type == ATTR: |
| 60 | # Edge Case: Handle incorrect number of elements for ATTR |
| 61 | if len(item) != 3: |
| 62 | raise TypeError("Graph item malformed") |
| 63 | key, value = item[1], item[2] |
| 64 | self.attrs[key] = value |
| 65 | |
| 66 | # Edge Case: Handle NODE items |
| 67 | elif item_type == NODE: |
| 68 | # Edge Case: Handle incorrect number of elements for NODE |
| 69 | if len(item) != 3: |
| 70 | raise TypeError("Graph item malformed") |
| 71 | name, attrs = item[1], item[2] |
| 72 | # Edge Case: Handle non-string node name |
| 73 | if not isinstance(name, str): |
| 74 | raise TypeError("Node name must be a string") |
| 75 | # Edge Case: Handle non-dict node attributes |
| 76 | if not isinstance(attrs, dict): |
| 77 | raise TypeError("Node attributes must be a dict") |
| 78 | self.nodes.append(Node(name, attrs)) |
| 79 | |
| 80 | # Edge Case: Handle EDGE items |
| 81 | elif item_type == EDGE: |
| 82 | # Edge Case: Handle incorrect number of elements for EDGE |
| 83 | if len(item) != 4: |
| 84 | raise TypeError("Graph item malformed") |
| 85 | src, dst, attrs = item[1], item[2], item[3] |
| 86 | # Edge Case: Handle non-string source or destination |
| 87 | if not isinstance(src, str) or not isinstance(dst, str): |
| 88 | raise TypeError("Edge source and destination must be strings") |
| 89 | # Edge Case: Handle non-dict edge attributes |
| 90 | if not isinstance(attrs, dict): |
| 91 | raise TypeError("Edge attributes must be a dict") |
| 92 | self.edges.append(Edge(src, dst, attrs)) |
| 93 | |
| 94 | # Handled Edge Cases: None input, non-list input, empty list, non-tuple items, empty tuples, unknown item types, incorrect number of elements for ATTR/NODE/EDGE, non-string node names, non-dict node attributes, non-string edge sources/destinations, non-dict edge attributes |