| 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 in data 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: 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 | # Process each item in the data list |
| 68 | for item in data: |
| 69 | # Edge Case: Graph item is not a tuple |
| 70 | if not isinstance(item, tuple): |
| 71 | raise TypeError("Graph item malformed") |
| 72 | |
| 73 | # Edge Case: Graph item is empty |
| 74 | if len(item) == 0: |
| 75 | raise TypeError("Graph item malformed") |
| 76 | |
| 77 | item_type = item[0] |
| 78 | |
| 79 | # Edge Case: Node item with incorrect number of elements |
| 80 | if item_type == NODE: |
| 81 | if len(item) != 3: |
| 82 | raise TypeError("Graph item malformed") |
| 83 | name, attrs = item[1], item[2] |
| 84 | # Edge Case: Node attributes is not a dict |
| 85 | if not isinstance(attrs, dict): |
| 86 | raise TypeError("Node attributes must be a dict") |
| 87 | self.nodes.append(Node(name, attrs)) |
| 88 | |
| 89 | # Edge Case: Edge item with incorrect number of elements |
| 90 | elif item_type == EDGE: |
| 91 | if len(item) != 4: |
| 92 | raise TypeError("Graph item malformed") |
| 93 | src, dst, attrs = item[1], item[2], item[3] |
| 94 | # Edge Case: Edge attributes is not a dict |
| 95 | if not isinstance(attrs, dict): |
| 96 | raise TypeError("Edge attributes must be a dict") |
| 97 | self.edges.append(Edge(src, dst, attrs)) |
| 98 | |
| 99 | # Edge Case: Attribute item with incorrect number of elements |
| 100 | elif item_type == ATTR: |
| 101 | if len(item) != 3: |
| 102 | raise TypeError("Graph item malformed") |
| 103 | key, value = item[1], item[2] |
| 104 | self.attrs[key] = value |
| 105 | |
| 106 | # Edge Case: Unknown item type |
| 107 | else: |
| 108 | raise ValueError("Unknown item") |
| 109 | |
| 110 | # Handled Edge Cases: None input, non-list data, non-tuple items, empty items, |
| 111 | # incorrect tuple lengths for NODE/EDGE/ATTR, non-dict attributes, |
| 112 | # unknown item types |