Created
February 9, 2023 23:01
-
-
Save brettvitaz/9b19aa9bf12d95397f222e5881c4d505 to your computer and use it in GitHub Desktop.
Prune dict for dataclass
This file contains hidden or 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
def prune_dict_for_dataclass(d: dict, cls): | |
ret = {} | |
for field in fields(cls): | |
if field.name in d: | |
if is_dataclass(field.type): | |
ret[field.name] = prune_dict_for_dataclass(d[field.name], field.type) | |
elif typing.get_origin(field.type) is list and type(d[field.name]) is list: | |
list_cls = typing.get_args(field.type)[0] | |
if is_dataclass(list_cls): | |
ret[field.name] = [prune_dict_for_dataclass(i, list_cls) for i in d[field.name]] | |
else: | |
ret[field.name] = d[field.name] | |
else: | |
ret[field.name] = d[field.name] | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment