def handle_identity_conversion(conversion: ResolvedConversion, tp: AnyType) -> ResolvedConversion: if (is_identity(conversion) and conversion.source == conversion.target and is_type_var(conversion.source)): return ResolvedConversion(replace(conversion, source=tp, target=tp)) else: return conversion
def subtyping_substitution( supertype: AnyType, subtype: AnyType ) -> Tuple[Mapping[AnyType, AnyType], Mapping[AnyType, AnyType]]: supertype, subtype = with_parameters(supertype), with_parameters(subtype) supertype_to_subtype, subtype_to_supertype = {}, {} super_origin = get_origin_or_type2(supertype) for base in generic_mro(subtype): base_origin = get_origin_or_type2(base) if base_origin == super_origin or (base_origin in ITERABLE_TYPES and super_origin in ITERABLE_TYPES): for base_arg, super_arg in zip(get_args(base), get_args(supertype)): if is_type_var(super_arg): supertype_to_subtype[super_arg] = base_arg if is_type_var(base_arg): subtype_to_supertype[base_arg] = super_arg break return supertype_to_subtype, subtype_to_supertype
def get_parameters(tp: AnyType) -> Iterable[TV]: if hasattr(tp, "__parameters__"): return tp.__parameters__ elif hasattr(tp, "__orig_bases__"): return _collect_type_vars(tp.__orig_bases__) elif is_type_var(tp): return (tp, ) else: return _type_vars
def instance_checker(tp: AnyType) -> Callable[[Any], bool]: tp = get_origin_or_type2(tp) if isinstance(tp, type): return lambda obj: isinstance(obj, tp) elif is_new_type(tp): return instance_checker(tp.__supertype__) elif is_type_var(tp): return lambda obj: True else: raise TypeError(f"{tp} is not supported in union serialization")
def check_type(self, tp: AnyType): if is_type_var(tp): raise TypeError("TypeVar cannot have a type_name") if has_type_vars(tp): if get_args(tp): raise TypeError("Generic alias cannot have a type_name") elif isinstance(self.json_schema, str) or isinstance(self.graphql, str): raise TypeError( "Unspecialized generic type must used factory type_name" )
def substitute_type_vars(tp: AnyType, substitution: Mapping[TV, AnyType]) -> AnyType: if is_type_var(tp): try: return substitution[tp] except KeyError: return Union[tp.__constraints__] if tp.__constraints__ else Any elif getattr(tp, "__parameters__", ()): return tp[tuple(substitution.get(p, p) for p in tp.__parameters__)] else: return tp
def has_type_vars(tp: AnyType) -> bool: return is_type_var(tp) or bool(getattr(tp, "__parameters__", ()))