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?
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