Skip to content

Instantly share code, notes, and snippets.

@okapies
Created March 12, 2021 03:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okapies/96d0242dfd48de6dc6def244b54f9836 to your computer and use it in GitHub Desktop.
Save okapies/96d0242dfd48de6dc6def244b54f9836 to your computer and use it in GitHub Desktop.
Construct a dataclass from a dict with unexpected keys
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)
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