| 23 | 23 | |
| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | """ |
| 27 | A class representing a graph structure that can be built from a DSL. |
| 28 | |
| 29 | The graph is constructed from a list of tuples that define nodes, edges, and attributes. |
| 30 | Each tuple must follow a specific format: |
| 31 | - ATTR: (ATTR, key, value) |
| 32 | - NODE: (NODE, name, attrs_dict) |
| 33 | - EDGE: (EDGE, src, dst, attrs_dict) |
| 34 | |
| 35 | Parameters: |
| 36 | data (list | None): A list of tuples describing the graph elements. |
| 37 | |
| 38 | Raises: |
| 39 | TypeError: If the data is not a list or if a tuple is malformed. |
| 40 | ValueError: If an unknown item type is encountered. |
| 41 | """ |
| 26 | 42 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 43 | # Edge Case: Handle None input by initializing empty collections |
| 44 | if data is None: |
| 45 | self.attrs = {} |
| 46 | self.nodes = [] |
| 47 | self.edges = [] |
| 48 | return |
| 49 | |
| 50 | # Edge Case: Ensure data is a list |
| 51 | if not isinstance(data, list): |
| 52 | raise TypeError("Graph data malformed") |
| 53 | |
| 54 | self.attrs = {} |
| 55 | self.nodes = [] |
| 56 | self.edges = [] |
| 57 | |
| 58 | # Process each item in the data list |
| 59 | for item in data: |
| 60 | # Edge Case: Ensure each item is a tuple |
| 61 | if not isinstance(item, tuple): |
| 62 | raise TypeError("Graph item malformed") |
| 63 | |
| 64 | # Edge Case: Ensure each tuple has at least one element |
| 65 | if len(item) < 1: |
| 66 | raise TypeError("Graph item malformed") |
| 67 | |
| 68 | item_type = item[0] |
| 69 | |
| 70 | # Edge Case: Handle ATTR type items |
| 71 | if item_type == ATTR: |
| 72 | if len(item) != 3: |
| 73 | raise TypeError("Graph item malformed") |
| 74 | _, key, value = item |
| 75 | self.attrs[key] = value |
| 76 | |
| 77 | # Edge Case: Handle NODE type items |
| 78 | elif item_type == NODE: |
| 79 | if len(item) != 3: |
| 80 | raise TypeError("Graph item malformed") |
| 81 | _, name, attrs = item |
| 82 | # Edge Case: Ensure node attributes is a dict |
| 83 | if not isinstance(attrs, dict): |
| 84 | raise TypeError("Node attributes must be a dictionary") |
| 85 | self.nodes.append(Node(name, attrs)) |
| 86 | |
| 87 | # Edge Case: Handle EDGE type items |
| 88 | elif item_type == EDGE: |
| 89 | if len(item) != 4: |
| 90 | raise TypeError("Graph item malformed") |
| 91 | _, src, dst, attrs = item |
| 92 | # Edge Case: Ensure edge attributes is a dict |
| 93 | if not isinstance(attrs, dict): |
| 94 | raise TypeError("Edge attributes must be a dictionary") |
| 95 | self.edges.append(Edge(src, dst, attrs)) |
| 96 | |
| 97 | # Edge Case: Handle unknown item types |
| 98 | else: |
| 99 | raise ValueError("Unknown item") |
| 100 | |
| 101 | # Handled Edge Cases: None input, non-list data, non-tuple items, tuples with insufficient elements, |
| 102 | # incorrect tuple lengths for each type, non-dict node/edge attributes, unknown item types |