Last active
February 14, 2024 10:04
-
-
Save alexanderankin/2a4549ac03554a31bef6eaaf2eaf7fd5 to your computer and use it in GitHub Desktop.
omits extra fields in python dataclasses like `@JsonIgnoreProperties(ignoreUnknown = true)`
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
from dataclasses import fields | |
from typing import TypeVar, Type | |
IPT = TypeVar('IPT') | |
def ignore_properties(cls: Type[IPT], dict_: any) -> IPT: | |
"""omits extra fields like @JsonIgnoreProperties(ignoreUnknown = true)""" | |
if isinstance(dict_, cls): return dict_ # noqa | |
class_fields = {f.name for f in fields(cls)} | |
filtered = {k: v for k, v in dict_.items() if k in class_fields} | |
return cls(**filtered) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment