Created
July 22, 2022 06:37
-
-
Save paxbun/3eb7d762a013f915fce69d4daecfab37 to your computer and use it in GitHub Desktop.
Python dataclass inverse of asdict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import is_dataclass, fields | |
from typing import TypeVar | |
T = TypeVar("T") | |
def fromdict(d: dict, ty: type[T]) -> T: | |
assert is_dataclass(ty) | |
for field in fields(ty): | |
if field.name in d: | |
if is_dataclass(field.type): | |
assert isinstance(d[field.name], dict) | |
d[field.name] = fromdict(d[field.name], field.type) | |
return ty(**d) | |
from dataclasses import dataclass, asdict | |
@dataclass | |
class Foo: | |
a: int = 5 | |
b: int = 6 | |
@dataclass | |
class Bar: | |
foo: Foo | |
c: int = 7 | |
b1 = Bar(foo=Foo()) | |
d = asdict(b1) | |
b2 = fromdict(d, Bar) | |
print(b1, b2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment