Home > Software design >  comparing types between a class and a dictionary
comparing types between a class and a dictionary

Time:11-29

I am working with dictionaries and classes and I want to check that the dictionaries and the classes have the same field types.

For example, I have a dataclass of this form

@dataclasses.dataclass
class FlatDataclass:
    first_field: str
    second_field: int

and I have a dictionary of this form

my_dict={first_field:"a_string", second_field:"5"}

I want to check that the values of the dictionary have the right type for the class.

So far I can get the types for the dictionary, from this:

dct_value_types = list(type(x).__name__ for x in list(dct.values()))

returns ['str', 'str']

however

[f.type for f in dataclasses.fields(klass)]

[<class 'str'>, <class 'int'>]

rather than ['str', 'str'], so I can't compare them.

How would you get the types in a way you can compare them?

CodePudding user response:

Either you do this

[f.type.__name__ for f in dataclasses.fields(klass)]

Or you do this

dct_value_types = list(type(x) for x in list(dct.values()))

Notice that I added or removed __name__ here, so both type checks should either have it or not

CodePudding user response:

You can use this function that checks if all the fields in the dataclass are present in a given dictionary and have same type -

def has_all_fields(d, custom_class):
    return all(field.name in d and isinstance(d[field.name], field.type) for field in dataclasses.fields(custom_class))

@dataclasses.dataclass
class FlatDataclass:
    first_field: str
    second_field: int

my_dict={"first_field":"a_string", "second_field":5}
print(has_all_fields(my_dict, FlatDataclass))

Output:

True

Note that this would still return True if dictionary has more fields than what the dataclass does.

  • Related