| 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 | - For ATTR: (ATTR, key, value) |
| 33 | - For NODE: (NODE, name, attrs_dict) |
| 34 | - For EDGE: (EDGE, src, dst, attrs_dict) |
| 35 | |
| 36 | Raises: |
| 37 | TypeError: If data is not a list or if any item is malformed |
| 38 | ValueError: If an unknown item type is encountered |
| 39 | """ |
| 40 | # Edge Case: Handle None input 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 | for item in data: |
| 56 | # Edge Case: Graph item is not a tuple |
| 57 | if not isinstance(item, tuple): |
| 58 | raise TypeError("Graph item malformed") |
| 59 | |
| 60 | # Edge Case: Empty tuple |
| 61 | if len(item) == 0: |
| 62 | raise TypeError("Graph item malformed") |
| 63 | |
| 64 | item_type = item[0] |
| 65 | |
| 66 | # Edge Case: Unknown item type |
| 67 | if item_type not in (NODE, EDGE, ATTR): |
| 68 | raise ValueError("Unknown item") |
| 69 | |
| 70 | # Edge Case: ATTR item with wrong number of elements |
| 71 | if item_type == ATTR: |
| 72 | if len(item) != 3: |
| 73 | raise TypeError("Graph item malformed") |
| 74 | self.attrs[item[1]] = item[2] |
| 75 | |
| 76 | # Edge Case: NODE item with wrong number of elements |
| 77 | elif item_type == NODE: |
| 78 | if len(item) != 3: |
| 79 | raise TypeError("Graph item malformed") |
| 80 | # Edge Case: Node attributes is not a dict |
| 81 | if not isinstance(item[2], dict): |
| 82 | raise TypeError("Graph item malformed") |
| 83 | self.nodes.append(Node(item[1], item[2])) |
| 84 | |
| 85 | # Edge Case: EDGE item with wrong number of elements |
| 86 | elif item_type == EDGE: |
| 87 | if len(item) != 4: |
| 88 | raise TypeError("Graph item malformed") |
| 89 | # Edge Case: Edge attributes is not a dict |
| 90 | if not isinstance(item[3], dict): |
| 91 | raise TypeError("Graph item malformed") |
| 92 | self.edges.append(Edge(item[1], item[2], item[3])) |
| 93 | |
| 94 | # Handled Edge Cases: None input, non-list data, non-tuple items, empty tuples, unknown item types, |
| 95 | # wrong number of elements for ATTR/NODE/EDGE, non-dict attributes for NODE/EDGE |