Upload type_utils.py with huggingface_hub
Browse files2 unmodified lines3456789101112131413 unmodified lines28293031323334355 unmodified lines4142434445464796 unmodified lines14414514614714814915035 unmodified lines18618718818919019119219319419519619719810 unmodified lines2092102112122132142152162178 unmodified lines22622722822923023123223323431 unmodified lines26626726826927027127227327411 unmodified lines28628728828929029129229329429529629 unmodified lines3263273283293303313323333343353363373383393403413423433443453463473483491 unmodified line3513523533543553563573583598 unmodified lines3683693703713723733748 unmodified lines3833843853863873883893903913923933943953963973983994001 unmodified line40240340440540640740840941015 unmodified lines4264274284294304314322 unmodified linesimport itertoolsimport typingdef isoftype(object, type):"""Checks if an object is of a certain typing type, including nested types.This function supports simple types (like `int`, `str`), typing types(like `List[int]`, `Tuple[str, int]`, `Dict[str, int]`), and nested typingtypes (like `List[List[int]]`, `Tuple[List[str], int]`, `Dict[str, List[int]]`).Args:13 unmodified lines>>> isoftype([[1, 2], [3, 4]], typing.List[typing.List[int]])True"""if hasattr(type, '__origin__'):origin = type.__origin__type_args = typing.get_args(type)5 unmodified linesreturn all(isoftype(element, type_arg) for element, type_arg in zip(object, type_args))else:return isinstance(object, type)# copied from: https://github.com/bojiang/typing_utils/blob/main/typing_utils/__init__.py# liscened under Apache License 2.096 unmodified linesget_origin(List[Tuple[T, T]][int]) == list```"""if hasattr(typing, 'get_origin'): # python 3.8+_getter = getattr(typing, "get_origin")ori = _getter(type_)elif hasattr(typing.List, "_special"): # python 3.735 unmodified linesget_args(Callable[[], T][int]) == ([], int)```"""if hasattr(typing, 'get_args'): # python 3.8+_getter = getattr(typing, "get_args")res = _getter(type_)elif hasattr(typing.List, "_special"): # python 3.7if (isinstance(type_, GenericClass) and not type_._special): # backport for python 3.8res = type_.__args__if get_origin(type_) is collections.abc.Callable and res[0] is not Ellipsis:res = (list(res[:-1]), res[-1])10 unmodified linesdef eval_forward_ref(ref, forward_refs=None):'''eval forward_refs in all cPython versions'''localns = forward_refs or {}if hasattr(typing, "_eval_type"): # python3.8 & python 3.98 unmodified linesclass NormalizedType(typing.NamedTuple):'''Normalized type, made it possible to compare, hash between types.'''origin: Typeargs: typing.Union[tuple, frozenset] = tuple()31 unmodified linesdef normalize(type_: Type) -> NormalizedType:'''convert types to NormalizedType instances.'''args = get_args(type_)origin = get_origin(type_)if not origin:11 unmodified linesif left is right:return Trueif (left is not Noneand left in STATIC_SUBTYPE_MAPPINGand right == STATIC_SUBTYPE_MAPPING[left]):return Trueif hasattr(left, "mro"):29 unmodified linesreturn True# Union[list, int] <> Union[typing.Sequence, int]return all(any(_is_normal_subtype(e, r, forward_refs) for r in right) for e in excluded)if isinstance(left, collections.abc.Sequence) and not isinstance(left, NormalizedType):if not isinstance(right, collections.abc.Sequence) or isinstance(right, NormalizedType):return Falseif (leftand left[-1].origin is not Ellipsisand rightand right[-1].origin is Ellipsis):# Tuple[type, type] <> Tuple[type, ...]return all(_is_origin_subtype_args(l, right[0], forward_refs) for l in left)1 unmodified linereturn Falsereturn all(l is not Noneand r is not Noneand _is_origin_subtype_args(l, r, forward_refs)for l, r in itertools.zip_longest(left, right))8 unmodified linesright: NormalizedType,forward_refs: typing.Optional[typing.Mapping[str, type]],) -> typing.Optional[bool]:if isinstance(left.origin, ForwardRef):left = normalize(eval_forward_ref(left.origin, forward_refs=forward_refs))8 unmodified linesif right.origin is typing.Union and left.origin is typing.Union:return _is_origin_subtype_args(left.args, right.args, forward_refs)if right.origin is typing.Union:return optional_any(_is_normal_subtype(left, a, forward_refs) for a in right.args)if left.origin is typing.Union:return optional_all(_is_normal_subtype(a, right, forward_refs) for a in left.args)# TypeVarif isinstance(left.origin, typing.TypeVar) and isinstance(right.origin, typing.TypeVar):if left.origin is right.origin:return True1 unmodified lineright_bound = getattr(right.origin, "__bound__", None)if right_bound is None or left_bound is None:return unknownreturn _is_normal_subtype(normalize(left_bound), normalize(right_bound), forward_refs)if isinstance(right.origin, typing.TypeVar):return unknownif isinstance(left.origin, typing.TypeVar):15 unmodified linesdef issubtype(left: Type, right: Type, forward_refs: typing.Optional[dict] = None,) -> typing.Optional[bool]:"""Check that the left argument is a subtype of the right.For unions, check if the type arguments of the left is a subset of the right.2 unmodified lines345678910111213141513 unmodified lines29303132333435365 unmodified lines424344454647484996 unmodified lines14614714814915015115235 unmodified lines18818919019119219319419519619719810 unmodified lines2092102112122132142152162178 unmodified lines22622722822923023123223323431 unmodified lines26626726826927027127227327411 unmodified lines28628728828929029129229 unmodified lines3223233243253263273283293303313323333341 unmodified line3363373383393403413428 unmodified lines3513523533543553568 unmodified lines3653663673683693703713723733743753761 unmodified line37837938038138238338415 unmodified lines4004014024034044054064074082 unmodified linesimport itertoolsimport typingdef isoftype(object, type):"""Checks if an object is of a certain typing type, including nested types.This function supports simple types (like `int`, `str`), typing types(like `List[int]`, `Tuple[str, int]`, `Dict[str, int]`), and nested typingtypes (like `List[List[int]]`, `Tuple[List[str], int]`, `Dict[str, List[int]]`).Args:13 unmodified lines>>> isoftype([[1, 2], [3, 4]], typing.List[typing.List[int]])True"""if hasattr(type, "__origin__"):origin = type.__origin__type_args = typing.get_args(type)5 unmodified linesreturn all(isoftype(element, type_arg) for element, type_arg in zip(object, type_args))else:return isinstance(object, type)# copied from: https://github.com/bojiang/typing_utils/blob/main/typing_utils/__init__.py# liscened under Apache License 2.096 unmodified linesget_origin(List[Tuple[T, T]][int]) == list```"""if hasattr(typing, "get_origin"): # python 3.8+_getter = getattr(typing, "get_origin")ori = _getter(type_)elif hasattr(typing.List, "_special"): # python 3.735 unmodified linesget_args(Callable[[], T][int]) == ([], int)```"""if hasattr(typing, "get_args"): # python 3.8+_getter = getattr(typing, "get_args")res = _getter(type_)elif hasattr(typing.List, "_special"): # python 3.7if isinstance(type_, GenericClass) and not type_._special: # backport for python 3.8res = type_.__args__if get_origin(type_) is collections.abc.Callable and res[0] is not Ellipsis:res = (list(res[:-1]), res[-1])10 unmodified linesdef eval_forward_ref(ref, forward_refs=None):"""eval forward_refs in all cPython versions"""localns = forward_refs or {}if hasattr(typing, "_eval_type"): # python3.8 & python 3.98 unmodified linesclass NormalizedType(typing.NamedTuple):"""Normalized type, made it possible to compare, hash between types."""origin: Typeargs: typing.Union[tuple, frozenset] = tuple()31 unmodified linesdef normalize(type_: Type) -> NormalizedType:"""convert types to NormalizedType instances."""args = get_args(type_)origin = get_origin(type_)if not origin:11 unmodified linesif left is right:return Trueif left is not None and left in STATIC_SUBTYPE_MAPPING and right == STATIC_SUBTYPE_MAPPING[left]:return Trueif hasattr(left, "mro"):29 unmodified linesreturn True# Union[list, int] <> Union[typing.Sequence, int]return all(any(_is_normal_subtype(e, r, forward_refs) for r in right) for e in excluded)if isinstance(left, collections.abc.Sequence) and not isinstance(left, NormalizedType):if not isinstance(right, collections.abc.Sequence) or isinstance(right, NormalizedType):return Falseif left and left[-1].origin is not Ellipsis and right and right[-1].origin is Ellipsis:# Tuple[type, type] <> Tuple[type, ...]return all(_is_origin_subtype_args(l, right[0], forward_refs) for l in left)1 unmodified linereturn Falsereturn all(l is not None and r is not None and _is_origin_subtype_args(l, r, forward_refs)for l, r in itertools.zip_longest(left, right))8 unmodified linesright: NormalizedType,forward_refs: typing.Optional[typing.Mapping[str, type]],) -> typing.Optional[bool]:if isinstance(left.origin, ForwardRef):left = normalize(eval_forward_ref(left.origin, forward_refs=forward_refs))8 unmodified linesif right.origin is typing.Union and left.origin is typing.Union:return _is_origin_subtype_args(left.args, right.args, forward_refs)if right.origin is typing.Union:return optional_any(_is_normal_subtype(left, a, forward_refs) for a in right.args)if left.origin is typing.Union:return optional_all(_is_normal_subtype(a, right, forward_refs) for a in left.args)# TypeVarif isinstance(left.origin, typing.TypeVar) and isinstance(right.origin, typing.TypeVar):if left.origin is right.origin:return True1 unmodified lineright_bound = getattr(right.origin, "__bound__", None)if right_bound is None or left_bound is None:return unknownreturn _is_normal_subtype(normalize(left_bound), normalize(right_bound), forward_refs)if isinstance(right.origin, typing.TypeVar):return unknownif isinstance(left.origin, typing.TypeVar):15 unmodified linesdef issubtype(left: Type,right: Type,forward_refs: typing.Optional[dict] = None,) -> typing.Optional[bool]:"""Check that the left argument is a subtype of the right.For unions, check if the type arguments of the left is a subset of the right.
type_utils.py+30-54