| 1 |
"""Implement a tiny subset of dataclasses_json for config.""" |
| 2 |
|
| 3 |
from collections.abc import Mapping, Sequence |
| 4 |
from dataclasses import asdict, fields, is_dataclass |
| 5 |
from typing import Any, Dict, Type |
| 6 |
|
| 7 |
|
| 8 |
class DataClassJsonMixin: |
| 9 |
"""Adds from_dict to dataclass.""" |
| 10 |
|
| 11 |
@classmethod |
| 12 |
def from_dict(cls, data: Dict[str, Any]) -> Any: |
| 13 |
"""Parse dataclasses recursively.""" |
| 14 |
kwargs: Dict[str, Any] = {} |
| 15 |
|
| 16 |
cls_fields = {field.name: field for field in fields(cls)} # type: ignore[arg-type] |
| 17 |
for key, value in data.items(): |
| 18 |
if key not in cls_fields: |
| 19 |
# Skip unknown fields |
| 20 |
continue |
| 21 |
|
| 22 |
field = cls_fields[key] |
| 23 |
if is_dataclass(field.type): |
| 24 |
assert issubclass(field.type, DataClassJsonMixin), field.type # type: ignore[arg-type,union-attr] |
| 25 |
kwargs[key] = field.type.from_dict(value) # type: ignore[union-attr] |
| 26 |
else: |
| 27 |
kwargs[key] = _decode(value, field.type) # type: ignore[arg-type] |
| 28 |
|
| 29 |
# Fill in optional fields with None |
| 30 |
for field in cls_fields.values(): |
| 31 |
if (field.name not in kwargs) and _is_optional(field.type): # type: ignore[arg-type] |
| 32 |
kwargs[field.name] = None |
| 33 |
|
| 34 |
return cls(**kwargs) |
| 35 |
|
| 36 |
def to_dict(self) -> Dict[str, Any]: |
| 37 |
"""Alias for asdict.""" |
| 38 |
return asdict(self) # type: ignore[call-overload] |
| 39 |
|
| 40 |
|
| 41 |
def _decode(value: Any, target_type: Type) -> Any: |
| 42 |
"""Decode value using (possibly generic) type.""" |
| 43 |
if is_dataclass(target_type): |
| 44 |
assert issubclass(target_type, DataClassJsonMixin), target_type |
| 45 |
return target_type.from_dict(value) if value is not None else None |
| 46 |
|
| 47 |
if hasattr(target_type, "__args__"): |
| 48 |
# Optional[T] |
| 49 |
if type(None) in target_type.__args__: |
| 50 |
optional_type = target_type.__args__[0] |
| 51 |
return _decode(value, optional_type) |
| 52 |
|
| 53 |
# List[T] |
| 54 |
if isinstance(value, Sequence): |
| 55 |
list_type = target_type.__args__[0] |
| 56 |
return [_decode(item, list_type) for item in value] |
| 57 |
|
| 58 |
# Dict[str, T] |
| 59 |
if isinstance(value, Mapping): |
| 60 |
value_type = target_type.__args__[1] |
| 61 |
return { |
| 62 |
map_key: _decode(map_value, value_type) |
| 63 |
for map_key, map_value in value.items() |
| 64 |
} |
| 65 |
|
| 66 |
return value |
| 67 |
|
| 68 |
|
| 69 |
def _is_optional(target_type: Type): |
| 70 |
"""True if type is Optional""" |
| 71 |
return hasattr(target_type, "__args__") and (type(None) in target_type.__args__) |