Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Last active February 14, 2024 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderankin/2a4549ac03554a31bef6eaaf2eaf7fd5 to your computer and use it in GitHub Desktop.
Save alexanderankin/2a4549ac03554a31bef6eaaf2eaf7fd5 to your computer and use it in GitHub Desktop.
omits extra fields in python dataclasses like `@JsonIgnoreProperties(ignoreUnknown = true)`
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