|
| 1 | +"""The list-from-dict implementation.""" |
| 2 | + |
| 3 | +from collections.abc import Mapping |
| 4 | +from typing import Any, TypeVar, get_args |
| 5 | + |
| 6 | +from .. import BaseConverter, SimpleStructureHook |
| 7 | +from ..dispatch import UnstructureHook |
| 8 | + |
| 9 | +T = TypeVar("T") |
| 10 | + |
| 11 | + |
| 12 | +def configure_list_from_dict( |
| 13 | + seq_type: list[T], field: str, converter: BaseConverter |
| 14 | +) -> tuple[SimpleStructureHook[Mapping, T], UnstructureHook]: |
| 15 | + """ |
| 16 | + Configure a list subtype to be structured and unstructured using a dictionary. |
| 17 | +
|
| 18 | + List elements have to be an attrs class or a dataclass. One field of the element |
| 19 | + type is extracted into a dictionary key; the rest of the data is stored under that |
| 20 | + key. |
| 21 | +
|
| 22 | + """ |
| 23 | + arg_type = get_args(seq_type)[0] |
| 24 | + |
| 25 | + arg_structure_hook = converter.get_structure_hook(arg_type, cache_result=False) |
| 26 | + |
| 27 | + def structure_hook( |
| 28 | + value: Mapping, type: Any = seq_type, _arg_type=arg_type |
| 29 | + ) -> list[T]: |
| 30 | + return [arg_structure_hook(v | {field: k}, _arg_type) for k, v in value.items()] |
| 31 | + |
| 32 | + arg_unstructure_hook = converter.get_unstructure_hook(arg_type, cache_result=False) |
| 33 | + |
| 34 | + def unstructure_hook(val: list[T]) -> dict: |
| 35 | + return { |
| 36 | + (unstructured := arg_unstructure_hook(v)).pop(field): unstructured |
| 37 | + for v in val |
| 38 | + } |
| 39 | + |
| 40 | + return structure_hook, unstructure_hook |
0 commit comments