|
1 | | -from pydantic import BaseModel, ConfigDict, Field |
| 1 | +from pydantic import BaseModel, ConfigDict, Field, field_validator |
2 | 2 | from typing import Annotated, List, Literal, Union |
3 | 3 |
|
4 | 4 | from schema.BaseElement import BaseElement |
@@ -29,6 +29,57 @@ class Line(BaseModel): |
29 | 29 | ] |
30 | 30 | ] |
31 | 31 |
|
| 32 | + @field_validator("line", mode="before") |
| 33 | + @classmethod |
| 34 | + def parse_list_of_dicts(cls, value): |
| 35 | + """This method inserts the key of the one-key dictionary into |
| 36 | + the name attribute of the elements""" |
| 37 | + if not isinstance(value, list): |
| 38 | + raise TypeError("line must be a list") |
| 39 | + |
| 40 | + if value and isinstance(value[0], BaseModel): |
| 41 | + # Already a list of models; nothing to do |
| 42 | + return value |
| 43 | + |
| 44 | + # we expect a list of dicts or strings |
| 45 | + elements = [] |
| 46 | + for item_dict in value: |
| 47 | + # an element is either a reference string to another element or a dict |
| 48 | + if isinstance(item_dict, str): |
| 49 | + raise RuntimeError("Reference/alias elements not yet implemented") |
| 50 | + |
| 51 | + elif isinstance(item_dict, dict): |
| 52 | + if not (isinstance(item_dict, dict) and len(item_dict) == 1): |
| 53 | + raise ValueError( |
| 54 | + f"Each line element must be a dict with exactly one key, the name of the element, but we got: {item_dict!r}" |
| 55 | + ) |
| 56 | + [(name, fields)] = item_dict.items() |
| 57 | + |
| 58 | + if not isinstance(fields, dict): |
| 59 | + raise ValueError( |
| 60 | + f"Value for element key '{name}' must be a dict (got {fields!r})" |
| 61 | + ) |
| 62 | + |
| 63 | + # Insert the name into the fields dict |
| 64 | + fields["name"] = name |
| 65 | + elements.append(fields) |
| 66 | + return elements |
| 67 | + |
| 68 | + def model_dump(self, *args, **kwargs): |
| 69 | + """This makes sure the element name property is moved out and up to a one-key dictionary""" |
| 70 | + # Use default dump for non-line fields |
| 71 | + data = super().model_dump(*args, **kwargs) |
| 72 | + |
| 73 | + # Reformat 'line' field as list of single-key dicts |
| 74 | + new_line = [] |
| 75 | + for elem in self.line: |
| 76 | + # Use custom dump for each line element |
| 77 | + elem_dict = elem.model_dump(**kwargs)[0] |
| 78 | + new_line.append(elem_dict) |
| 79 | + |
| 80 | + data["line"] = new_line |
| 81 | + return data |
| 82 | + |
32 | 83 |
|
33 | 84 | # Avoid circular import issues |
34 | 85 | Line.model_rebuild() |
0 commit comments