Skip to content

Instantly share code, notes, and snippets.

@paxbun
Created July 22, 2022 06:37
Show Gist options
  • Save paxbun/3eb7d762a013f915fce69d4daecfab37 to your computer and use it in GitHub Desktop.
Save paxbun/3eb7d762a013f915fce69d4daecfab37 to your computer and use it in GitHub Desktop.
Python dataclass inverse of asdict
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