| 24 | 39 | |
| 25 | 40 | class Graph: |
| 26 | 41 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 42 | """ |
| 43 | Initialize a Graph with data. |
| 44 | |
| 45 | Parameters: |
| 46 | data (list): A list of tuples describing the graph elements. |
| 47 | |
| 48 | Raises: |
| 49 | TypeError: If data is not a list or if any item is malformed. |
| 50 | ValueError: If an unknown item type is encountered. |
| 51 | """ |
| 52 | # Edge Case: Handle None data by initializing empty collections |
| 53 | if data is None: |
| 54 | self.nodes = [] |
| 55 | self.edges = [] |
| 56 | self.attrs = {} |
| 57 | return |
| 58 | |
| 59 | # Edge Case: Graph data is not a list |
| 60 | if not isinstance(data, list): |
| 61 | raise TypeError("Graph data malformed") |
| 62 | |
| 63 | self.nodes = [] |
| 64 | self.edges = [] |
| 65 | self.attrs = {} |
| 66 | |
| 67 | for item in data: |
| 68 | # Edge Case: Graph item is not a tuple |
| 69 | if not isinstance(item, tuple): |
| 70 | raise TypeError("Graph item malformed") |
| 71 | |
| 72 | # Edge Case: Empty tuple |
| 73 | if len(item) == 0: |
| 74 | raise TypeError("Graph item malformed") |
| 75 | |
| 76 | item_type = item[0] |
| 77 | |
| 78 | # Edge Case: Node item with incorrect number of elements |
| 79 | if item_type == NODE: |
| 80 | if len(item) != 3: |
| 81 | raise TypeError("Graph item malformed") |
| 82 | name, attrs = item[1], item[2] |
| 83 | # Edge Case: Node attributes is not a dict |
| 84 | if not isinstance(attrs, dict): |
| 85 | raise TypeError("Node attributes must be a dictionary") |
| 86 | self.nodes.append(Node(name, attrs)) |
| 87 | |
| 88 | # Edge Case: Edge item with incorrect number of elements |
| 89 | elif item_type == EDGE: |
| 90 | if len(item) != 4: |
| 91 | raise TypeError("Graph item malformed") |
| 92 | src, dst, attrs = item[1], item[2], item[3] |
| 93 | # Edge Case: Edge attributes is not a dict |
| 94 | if not isinstance(attrs, dict): |
| 95 | raise TypeError("Edge attributes must be a dictionary") |
| 96 | self.edges.append(Edge(src, dst, attrs)) |
| 97 | |
| 98 | # Edge Case: Attribute item with incorrect number of elements |
| 99 | elif item_type == ATTR: |
| 100 | if len(item) != 3: |
| 101 | raise TypeError("Graph item malformed") |
| 102 | key, value = item[1], item[2] |
| 103 | self.attrs[key] = value |
| 104 | |
| 105 | # Edge Case: Unknown item type |
| 106 | else: |
| 107 | raise ValueError("Unknown item") |
| 108 | # Handled Edge Cases: None data, non-list data, non-tuple items, empty tuples, |
| 109 | # incorrect tuple lengths for NODE/EDGE/ATTR, non-dict attributes, unknown item types |