Construct a dataclass from a dict with unexpected keys
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 asdict, fields | |
from typing import Any, Dict | |
class DataClassBase: | |
@classmethod | |
def fromdict(cls, d: Dict[str, Any]): | |
"""Return a dataclass from a dict which may include unexpected keys.""" | |
class_fields = {f.name for f in fields(cls)} | |
return cls(**{k: v for k, v in d.items() if k in class_fields}) | |
def asdict(self): | |
"""Return the fields of a dataclass instance as a new dictionary mapping field names to | |
field values.""" | |
return asdict(self) |
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 dataclass | |
from dataclass_util import DataClassBase | |
@dataclass | |
class Person(DataClassBase): | |
name: str | |
age: int | |
person = Person.fromdict({'name': 'John Doe', 'age': 42, 'address': None}) | |
print(person.asdict()) # {'name': 'John Doe', 'age': 42} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment