def _deserialize(self, value, attr, data, **kwargs): if isinstance(value, dict) and '__type' in value: dc_name = value['__type'] for type_, schema_ in self.desc.items(): if is_dataclass(type_) and type_.__name__ == dc_name: del value['__type'] return schema_._deserialize(value, attr, data, **kwargs) for type_, schema_ in self.desc.items(): if isinstance(value, _get_type_origin(type_)): return schema_._deserialize(value, attr, data, **kwargs) else: warnings.warn( f'The type "{type(value).__name__}" (value: "{value}") ' f'is not in the list of possible types of typing.Union ' f'(dataclass: {self.cls.__name__}, field: {self.field.name}). ' f'Value cannot be deserialized properly.') return super()._deserialize(value, attr, data, **kwargs)
def _serialize(self, value, attr, obj, **kwargs): if self.allow_none and value is None: return None for type_, schema_ in self.desc.items(): if _issubclass_safe(type(value), type_): if is_dataclass(value): res = schema_._serialize(value, attr, obj, **kwargs) res['__type'] = str(type_.__name__) return res break elif isinstance(value, _get_type_origin(type_)): return schema_._serialize(value, attr, obj, **kwargs) else: warnings.warn( f'The type "{type(value).__name__}" (value: "{value}") ' f'is not in the list of possible types of typing.Union ' f'(dataclass: {self.cls.__name__}, field: {self.field.name}). ' f'Value cannot be serialized properly.') return super()._serialize(value, attr, obj, **kwargs)
def _decode_dict_keys(key_type, xs, infer_missing): """ Because JSON object keys must be strs, we need the extra step of decoding them back into the user's chosen python type """ decode_function = key_type # handle NoneType keys... it's weird to type a Dict as NoneType keys # but it's valid... if key_type is None or key_type == Any: decode_function = key_type = (lambda x: x) # handle a nested python dict that has tuples for keys. E.g. for # Dict[Tuple[int], int], key_type will be typing.Tuple[int], but # decode_function should be tuple, so map() doesn't break. # # Note: _get_type_origin() will return typing.Tuple for python # 3.6 and tuple for 3.7 and higher. elif _get_type_origin(key_type) in {tuple, Tuple}: decode_function = tuple key_type = key_type return map(decode_function, _decode_items(key_type, xs, infer_missing))