| 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 treating it as an empty list |
| 41 | if data is None: |
| 42 | data = [] |
| 43 | |
| 44 | # Edge Case: Graph data is not a list |
| 45 | if not isinstance(data, list): |
| 46 | raise TypeError("Graph data malformed") |
| 47 | |
| 48 | self.nodes = [] |
| 49 | self.edges = [] |
| 50 | self.attrs = {} |
| 51 | |
| 52 | # Process each item in the data list |
| 53 | for item in data: |
| 54 | # Edge Case: Graph item is not a tuple |
| 55 | if not isinstance(item, tuple): |
| 56 | raise TypeError("Graph item malformed") |
| 57 | |
| 58 | # Edge Case: Graph item is empty |
| 59 | if len(item) == 0: |
| 60 | raise TypeError("Graph item malformed") |
| 61 | |
| 62 | item_type = item[0] |
| 63 | |
| 64 | # Edge Case: Unknown item type |
| 65 | if item_type not in (NODE, EDGE, ATTR): |
| 66 | raise ValueError("Unknown item") |
| 67 | |
| 68 | # Process attribute |
| 69 | if item_type == ATTR: |
| 70 | # Edge Case: Attribute tuple doesn't have exactly 3 elements |
| 71 | if len(item) != 3: |
| 72 | raise TypeError("Graph item malformed") |
| 73 | |
| 74 | _, key, value = item |
| 75 | self.attrs[key] = value |
| 76 | |
| 77 | # Process node |
| 78 | elif item_type == NODE: |
| 79 | # Edge Case: Node tuple doesn't have exactly 3 elements |
| 80 | if len(item) != 3: |
| 81 | raise TypeError("Graph item malformed") |
| 82 | |
| 83 | _, name, attrs = item |
| 84 | # Edge Case: Node attributes is not a dict |
| 85 | if not isinstance(attrs, dict): |
| 86 | raise TypeError("Graph item malformed") |
| 87 | |
| 88 | self.nodes.append(Node(name, attrs)) |
| 89 | |
| 90 | # Process edge |
| 91 | elif item_type == EDGE: |
| 92 | # Edge Case: Edge tuple doesn't have exactly 4 elements |
| 93 | if len(item) != 4: |
| 94 | raise TypeError("Graph item malformed") |
| 95 | |
| 96 | _, src, dst, attrs = item |
| 97 | # Edge Case: Edge attributes is not a dict |
| 98 | if not isinstance(attrs, dict): |
| 99 | raise TypeError("Graph item malformed") |
| 100 | |
| 101 | self.edges.append(Edge(src, dst, attrs)) |
| 102 | |
| 103 | # Handled Edge Cases: None input, non-list data, non-tuple items, empty items, unknown item types, |
| 104 | # incorrect tuple lengths for attributes/nodes/edges, non-dict attributes for nodes/edges |