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