Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to safely initialize a dataclass based on a dict with unexpected keys?

Tags:

python

html

I'd like to initialize A from a dict which can contain unexpected keys. I'd like to initialize with the given, known keys and ignore the rest

from dataclasses import dataclass

@dataclass
class A:
    a: str
    b: int

a1 = A(**{'a': 'Foo', 'b': 123})  # works
a2 = A(**{'a': 'Foo', 'b': 123, 'c': 'unexpected'})  # raises TypeError

Is there a Python feature that I'm missing or do I have to filter the dict upfront?

like image 661
Yash Shukla Avatar asked Jan 30 '26 00:01

Yash Shukla


1 Answers

Another option is to use the dataclasses.fields function with a classmethod.

from dataclasses import dataclass, fields


@dataclass
class A:
    a: str
    b: int

    @classmethod
    def from_dict(cls, d: dict) -> "A":
        field_names = {field.name for field in fields(cls)}
        return cls(**{k: v for k, v in d.items() if k in field_names})

a1 = A.from_dict({'a': 'Foo', 'b': 123})
a2 = A.from_dict({'a': 'Foo', 'b': 123, 'c': 'unexpected, but who cares?'})
like image 108
Tomer Ariel Avatar answered Feb 01 '26 15:02

Tomer Ariel