|
| 1 | +from typing import Any, Dict, List, Union, NewType, get_type_hints |
| 2 | +from dataclasses import dataclass, field, asdict |
| 3 | +from dacite import from_dict, Config, ForwardReferenceError, UnexpectedDataError, StrictUnionMatchError |
| 4 | +import yaml |
| 5 | +import warnings |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import sys |
| 9 | + |
| 10 | +debug = 3 # global variables |
| 11 | +log = logging.getLogger(__name__) # logging |
| 12 | +if debug > 2: |
| 13 | + logging.basicConfig(level=logging.DEBUG) |
| 14 | +elif debug > 1: |
| 15 | + logging.basicConfig(level=logging.INFO) |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class X: |
| 19 | + i: int |
| 20 | + j: int |
| 21 | + |
| 22 | +@dataclass |
| 23 | +class Y: |
| 24 | + children: Dict[Union[str, int], X] |
| 25 | + def to_dict(self) -> Dict[str, Any]: |
| 26 | + return asdict(self) |
| 27 | + |
| 28 | +d = {"children": {1: {"i": 42, "j": 43}, 2: {"i": 37, "j": 38}}} # Test Dict |
| 29 | +result = from_dict(Y, d) |
| 30 | +print ("Dict d: ...............", d) |
| 31 | +print ("Class result: .........", result) |
| 32 | +print ("YAML result: ..........\n", yaml.dump(result.to_dict(), sort_keys=False, indent=2, default_flow_style=False), "\n") |
| 33 | +print ("Dict result.to_dict(): ", result.to_dict()) |
| 34 | +assert result == Y(children={1: X(i=42, j=43), 2: X(i=37, j=38)}) |
0 commit comments