def validate_type(data, type_):
instance_check = False
abstract_types = {typing.AbstractSet, typing.Sequence, typing.Mapping}
if hasattr(type_, '__origin__') and type_.__origin__ in abstract_types:
param_type = get_abstract_param_types(type_)
imp_types = {
typing.AbstractSet: collections.Set,
typing.Sequence: collections.Sequence,
typing.Mapping: collections.Mapping,
}
instance_check = isinstance(data, imp_types[type_.__origin__]) and \
all(isinstance(item, param_type[0]) for item in data)
else:
try:
instance_check = isinstance(data, type_)
except TypeError:
if is_union_type(type_):
instance_check = any(
isinstance(data, t) for t in get_union_types(type_)
)
else:
raise ValueError('{!r} cannot validated.'.format(type_))
return instance_check
评论列表
文章目录