def _into_union(value: V, kls: Type[T]) -> Result[T]: types = get_args(kls) err = Error(ty=kls, value=value) for ty in types: ret = into(value, ty) if not is_error(ret): return ret return err
def check_mono_container( value: Any, ty: Union[Type[List[Any]], Type[Set[Any]], Type[FrozenSet[Any]]]) -> Result: ty_item = get_args(ty)[0] for v in value: err = check(v, ty_item) if is_error(err): return err return None
def check_tuple(value: Any, ty: Type[Tuple[Any, ...]]) -> Result: types = get_args(ty) if len(value) != len(types): return Error0(ty=ty, value=value) for v, t in zip(value, types): err = check(v, t) if is_error(err): return err return None
def check_dict(value: Dict[Any, Any], ty: Type[Dict[Any, Any]]) -> Result: args = get_args(ty) ty_key = args[0] ty_item = args[1] for k, v in value.items(): err = check(k, ty_key) if is_error(err): return err err = check(v, ty_item) if err is not None: err.path.append(k) return err return None
def _into_mono_container(value: V, kls: Type[T]) -> Result[T]: if isinstance(value, str): return Error(kls, value) if not _is_sized_iterable(value): return Error(kls, value) ty_item = get_args(kls)[0] ty_orig = get_origin(kls) assert ty_orig ret: List[T] = [] for v in cast(Iterable[T], value): w = into(v, ty_item) # type: ignore if isinstance(w, Error): return w ret.append(w) return ty_orig(ret)
def _into_dict(value: V, kls: Type[T]) -> Result[T]: if not isinstance(value, dict): return Error(kls, value) args = get_args(kls) ty_key = args[0] ty_item = args[1] orig = get_origin(kls) assert orig is not None ret = orig() for k, v in value.items(): kr = into(k, ty_key) if is_error(kr): return kr vr = into(v, ty_item) if is_error(vr): vr.path.append(k) return vr ret[kr] = vr return ret
def _into_tuple(value: V, kls: Type[T]) -> Result[T]: if not _is_sized_iterable(value): return Error(kls, value) types = get_args(kls) val0: Sized = value # type: ignore if len(types) != len(val0): return Error(ty=kls, value=val0) val1: Iterable[T] = value # type: ignore ret: List[T] = [] for v, t in zip(val1, types): vr = into(v, t) # type: ignore if isinstance(vr, Error): return vr ret.append(vr) ty_orig = get_origin(kls) assert ty_orig is not None return ty_orig(ret)
def check_union(value: Any, ty: Type[Any]) -> Result: if any(not is_error(check(value, t)) for t in get_args(ty)): return None return Error0(ty=ty, value=value)
def check_literal(value: Any, ty: Type[Any]) -> Result: if all(value != t for t in get_args(ty)): return Error0(ty=ty, value=value) return None
def _into_literal(value: V, kls: Type[T]) -> Result[T]: literals = get_args(kls) if value not in literals: return Error(kls, value) return value # type: ignore