| 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 | None): 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 input by initializing empty collections |
| 53 | if data is None: |
| 54 | self.nodes = [] |
| 55 | self.edges = [] |
| 56 | self.attrs = {} |
| 57 | return |
| 58 | |
| 59 | # Edge Case: 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 | # Process each item in the data list |
| 68 | for item in data: |
| 69 | # Edge Case: Item is not a tuple |
| 70 | if not isinstance(item, tuple): |
| 71 | raise TypeError("Graph item malformed") |
| 72 | |
| 73 | # Edge Case: Empty tuple |
| 74 | if len(item) == 0: |
| 75 | raise TypeError("Graph item malformed") |
| 76 | |
| 77 | item_type = item[0] |
| 78 | |
| 79 | # Edge Case: Item type is ATTR |
| 80 | if item_type == ATTR: |
| 81 | # Edge Case: Wrong number of elements for ATTR |
| 82 | if len(item) != 3: |
| 83 | raise TypeError("Graph item malformed") |
| 84 | |
| 85 | _, key, value = item |
| 86 | self.attrs[key] = value |
| 87 | |
| 88 | # Edge Case: Item type is NODE |
| 89 | elif item_type == NODE: |
| 90 | # Edge Case: Wrong number of elements for NODE |
| 91 | if len(item) != 3: |
| 92 | raise TypeError("Graph item malformed") |
| 93 | |
| 94 | _, name, attrs = item |
| 95 | # Edge Case: Node attributes is not a dict |
| 96 | if not isinstance(attrs, dict): |
| 97 | raise TypeError("Node attributes must be a dictionary") |
| 98 | |
| 99 | self.nodes.append(Node(name, attrs)) |
| 100 | |
| 101 | # Edge Case: Item type is EDGE |
| 102 | elif item_type == EDGE: |
| 103 | # Edge Case: Wrong number of elements for EDGE |
| 104 | if len(item) != 4: |
| 105 | raise TypeError("Graph item malformed") |
| 106 | |
| 107 | _, src, dst, attrs = item |
| 108 | # Edge Case: Edge attributes is not a dict |
| 109 | if not isinstance(attrs, dict): |
| 110 | raise TypeError("Edge attributes must be a dictionary") |
| 111 | |
| 112 | self.edges.append(Edge(src, dst, attrs)) |
| 113 | |
| 114 | # Edge Case: Unknown item type |
| 115 | else: |
| 116 | raise ValueError("Unknown item") |
| 117 | |
| 118 | # Handled Edge Cases: None input, data not a list, item not a tuple, empty tuple, wrong number of elements for ATTR/NODE/EDGE, node/edge attributes not dict, unknown item type |