🔥 Remove unused functionality from `_typing.py` file (#805)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Iván Todorovich · committed by GitHub · parent fc2a634 · Browse files · 4 files·+7 added−481 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: svlandeg <svlandeg@github.com>
Diff stats
4 files+7 added−481 removed
- other:+7 added−481 removed
Provenance
- Commit
67a9eee- Tree
ae99a86- Author
Iván Todorovich <ivan.todorovich@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
fc2a634
4 files changed+7 added−481 removed
modified:typer/_typing.py+3 added-474 removed
1 # Copied from pydantic 1.9.2 (the latest version to support python 3.6.)2 # https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py3+# Reduced drastically to only include Typer-specific 3.7+ functionality4 # mypy: ignore-errors5 6 import sys6-from collections.abc import Callable as Callable7-from os import PathLike7 from typing import (9- TYPE_CHECKING,10- AbstractSet,8 Any,12- ClassVar,13- Dict,14- ForwardRef,15- Generator,16- List,17- Mapping,18- NewType,9+ Callable,10 Optional,20- Sequence,21- Set,11 Tuple,12 Type,13 Union,25- _eval_type,26- cast,27- get_type_hints,14 )29-from typing import Callable as TypingCallable15 31-from typing_extensions import Annotated, Literal16+from typing_extensions import Literal, get_args, get_origin17 33-AnyCallable = TypingCallable[..., Any]34-NoArgAnyCallable = TypingCallable[[], Any]35-36-try:37- from typing import _TypingBase as typing_base # type: ignore38-except ImportError:39- from typing import _Final as typing_base # type: ignore40-41-try:42- from typing import GenericAlias as TypingGenericAlias # type: ignore43-except ImportError:44- # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on)45- TypingGenericAlias = ()46-47-try:48- from types import UnionType as TypesUnionType # type: ignore49-except ImportError:50- # python < 3.10 does not have UnionType (str | int, byte | bool and so on)51- TypesUnionType = ()52-53-54-if sys.version_info < (3, 9):55-56- def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:57- return type_._evaluate(globalns, localns)58-59-else:60-61- def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:62- # Even though it is the right signature for python 3.9, mypy complains with63- # `error: Too many arguments for "_evaluate" of "ForwardRef"` hence the cast...64- return cast(Any, type_)._evaluate(globalns, localns, set())65-66-67-if sys.version_info < (3, 9):68- # Ensure we always get all the whole `Annotated` hint, not just the annotated type.69- # For 3.7 to 3.8, `get_type_hints` doesn't recognize `typing_extensions.Annotated`,70- # so it already returns the full annotation71- get_all_type_hints = get_type_hints72-73-else:74-75- def get_all_type_hints(obj: Any, globalns: Any = None, localns: Any = None) -> Any:76- return get_type_hints(obj, globalns, localns, include_extras=True)77-78-79-# Annotated[...] is implemented by returning an instance of one of these classes, depending on80-# python/typing_extensions version.81-AnnotatedTypeNames = {"AnnotatedMeta", "_AnnotatedAlias"}82-83-84-if sys.version_info < (3, 8):85-86- def get_origin(t: Type[Any]) -> Optional[Type[Any]]:87- if type(t).__name__ in AnnotatedTypeNames:88- return cast(89- Type[Any], Annotated90- ) # mypy complains about _SpecialForm in py3.691- return getattr(t, "__origin__", None)92-93-else:94- from typing import get_origin as _typing_get_origin95-96- def get_origin(tp: Type[Any]) -> Optional[Type[Any]]:97- """98- We can't directly use `typing.get_origin` since we need a fallback to support99- custom generic classes like `ConstrainedList`100- It should be useless once https://github.com/cython/cython/issues/3537 is101- solved and https://github.com/samuelcolvin/pydantic/pull/1753 is merged.102- """103- if type(tp).__name__ in AnnotatedTypeNames:104- return cast(Type[Any], Annotated) # mypy complains about _SpecialForm105- return _typing_get_origin(tp) or getattr(tp, "__origin__", None)106-107-108-if sys.version_info < (3, 8): # noqa: C901109- from typing import _GenericAlias110-111- def get_args(t: Type[Any]) -> Tuple[Any, ...]:112- """Compatibility version of get_args for python 3.7.113-114- Mostly compatible with the python 3.8 `typing` module version115- and able to handle almost all use cases.116- """117- if type(t).__name__ in AnnotatedTypeNames:118- return t.__args__ + t.__metadata__119- if isinstance(t, _GenericAlias):120- res = t.__args__121- if t.__origin__ is Callable and res and res[0] is not Ellipsis:122- res = (list(res[:-1]), res[-1])123- return res124- return getattr(t, "__args__", ())125-126-else:127- from typing import get_args as _typing_get_args128-129- def _generic_get_args(tp: Type[Any]) -> Tuple[Any, ...]:130- """131- In python 3.9, `typing.Dict`, `typing.List`, ...132- do have an empty `__args__` by default (instead of the generic ~T for example).133- In order to still support `Dict` for example and consider it as `Dict[Any, Any]`,134- we retrieve the `_nparams` value that tells us how many parameters it needs.135- """136- if hasattr(tp, "_nparams"):137- return (Any,) * tp._nparams138- return ()139-140- def get_args(tp: Type[Any]) -> Tuple[Any, ...]:141- """Get type arguments with all substitutions performed.142-143- For unions, basic simplifications used by Union constructor are performed.144- Examples::145- get_args(Dict[str, int]) == (str, int)146- get_args(int) == ()147- get_args(Union[int, Union[T, int], str][int]) == (int, str)148- get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])149- get_args(Callable[[], T][int]) == ([], int)150- """151- if type(tp).__name__ in AnnotatedTypeNames:152- return tp.__args__ + tp.__metadata__153- # the fallback is needed for the same reasons as `get_origin` (see above)154- return (155- _typing_get_args(tp) or getattr(tp, "__args__", ()) or _generic_get_args(tp)156- )157-158-159-if sys.version_info < (3, 9):160-161- def convert_generics(tp: Type[Any]) -> Type[Any]:162- """Python 3.9 and older only supports generics from `typing` module.163- They convert strings to ForwardRef automatically.164-165- Examples::166- typing.List['Hero'] == typing.List[ForwardRef('Hero')]167- """168- return tp169-170-else:171- from typing import _UnionGenericAlias # type: ignore172-173- from typing_extensions import _AnnotatedAlias174-175- def convert_generics(tp: Type[Any]) -> Type[Any]:176- """177- Recursively searches for `str` type hints and replaces them with ForwardRef.178-179- Examples::180- convert_generics(list['Hero']) == list[ForwardRef('Hero')]181- convert_generics(dict['Hero', 'Team']) == dict[ForwardRef('Hero'), ForwardRef('Team')]182- convert_generics(typing.Dict['Hero', 'Team']) == typing.Dict[ForwardRef('Hero'), ForwardRef('Team')]183- convert_generics(list[str | 'Hero'] | int) == list[str | ForwardRef('Hero')] | int184- """185- origin = get_origin(tp)186- if not origin or not hasattr(tp, "__args__"):187- return tp188-189- args = get_args(tp)190-191- # typing.Annotated needs special treatment192- if origin is Annotated:193- return _AnnotatedAlias(convert_generics(args[0]), args[1:])194-195- # recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)`196- converted = tuple(197- ForwardRef(arg)198- if isinstance(arg, str) and isinstance(tp, TypingGenericAlias)199- else convert_generics(arg)200- for arg in args201- )202-203- if converted == args:204- return tp205- elif isinstance(tp, TypingGenericAlias):206- return TypingGenericAlias(origin, converted)207- elif isinstance(tp, TypesUnionType):208- # recreate types.UnionType (PEP604, Python >= 3.10)209- return _UnionGenericAlias(origin, converted)210- else:211- try:212- setattr(tp, "__args__", converted) # noqa: B010213- except AttributeError:214- pass215- return tp216-217-18 if sys.version_info < (3, 10):19 20 def is_union(tp: Optional[Type[Any]]) -> bool:21 return tp is Union22 223- WithArgsTypes = (TypingGenericAlias,)224-23 else:24 import types227- import typing25 26 def is_union(tp: Optional[Type[Any]]) -> bool:27 return tp is Union or tp is types.UnionType # noqa: E72128 232- WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType)29 234-235-if sys.version_info < (3, 9):236- StrPath = Union[str, PathLike]237-else:238- StrPath = Union[str, PathLike]239- # TODO: Once we switch to Cython 3 to handle generics properly240- # (https://github.com/cython/cython/issues/2753), use following lines instead241- # of the one above242- # # os.PathLike only becomes subscriptable from Python 3.9 onwards243- # StrPath = Union[str, PathLike[str]]244-245-246-if TYPE_CHECKING:247- # Only in Pydantic248- # from .fields import ModelField249-250- TupleGenerator = Generator[Tuple[str, Any], None, None]251- DictStrAny = Dict[str, Any]252- DictAny = Dict[Any, Any]253- SetStr = Set[str]254- ListStr = List[str]255- IntStr = Union[int, str]256- AbstractSetIntStr = AbstractSet[IntStr]257- DictIntStrAny = Dict[IntStr, Any]258- MappingIntStrAny = Mapping[IntStr, Any]259- CallableGenerator = Generator[AnyCallable, None, None]260- ReprArgs = Sequence[Tuple[Optional[str], Any]]261- AnyClassMethod = classmethod[Any]262-30 __all__ = (264- "ForwardRef",265- "Callable",266- "AnyCallable",267- "NoArgAnyCallable",31 "NoneType",32 "is_none_type",270- "display_as_type",271- "resolve_annotations",33 "is_callable_type",34 "is_literal_type",35 "all_literal_values",275- "is_namedtuple",276- "is_typeddict",277- "is_new_type",278- "new_type_supertype",279- "is_classvar",280- "update_field_forward_refs",281- "update_model_forward_refs",282- "TupleGenerator",283- "DictStrAny",284- "DictAny",285- "SetStr",286- "ListStr",287- "IntStr",288- "AbstractSetIntStr",289- "DictIntStrAny",290- "CallableGenerator",291- "ReprArgs",292- "AnyClassMethod",293- "CallableGenerator",294- "WithArgsTypes",295- "get_args",296- "get_origin",297- "get_sub_types",298- "typing_base",299- "get_all_type_hints",36 "is_union",301- "StrPath",37 )38 39 40 NoneType = None.__class__32 unmodified lines73 return True74 return False75 76 342-def display_as_type(v: Type[Any]) -> str:343- if (344- not isinstance(v, typing_base)345- and not isinstance(v, WithArgsTypes)346- and not isinstance(v, type)347- ):348- v = v.__class__349-350- if is_union(get_origin(v)):351- return f'Union[{", ".join(map(display_as_type, get_args(v)))}]'352-353- if isinstance(v, WithArgsTypes):354- # Generic alias are constructs like `list[int]`355- return str(v).replace("typing.", "")356-357- try:358- return v.__name__359- except AttributeError:360- # happens with typing objects361- return str(v).replace("typing.", "")362-363-364-def resolve_annotations(365- raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]366-) -> Dict[str, Type[Any]]:367- """368- Partially taken from typing.get_type_hints.369-370- Resolve string or ForwardRef annotations into type objects if possible.371- """372- base_globals: Optional[Dict[str, Any]] = None373- if module_name:374- try:375- module = sys.modules[module_name]376- except KeyError:377- # happens occasionally, see https://github.com/samuelcolvin/pydantic/issues/2363378- pass379- else:380- base_globals = module.__dict__381-382- annotations = {}383- for name, value in raw_annotations.items():384- if isinstance(value, str):385- if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (386- 3,387- 10,388- 1,389- ):390- value = ForwardRef(value, is_argument=False, is_class=True)391- else:392- value = ForwardRef(value, is_argument=False)393- try:394- value = _eval_type(value, base_globals, None)395- except NameError:396- # this is ok, it can be fixed with update_forward_refs397- pass398- annotations[name] = value399- return annotations400-401-77 def is_callable_type(type_: Type[Any]) -> bool:78 return type_ is Callable or get_origin(type_) is Callable79 80 15 unmodified lines96 return (type_,)97 98 values = literal_values(type_)99 return tuple(x for value in values for x in all_literal_values(value))425-426-427-def is_namedtuple(type_: Type[Any]) -> bool:428- """429- Check if a given class is a named tuple.430- It can be either a `typing.NamedTuple` or `collections.namedtuple`431- """432- from .utils import lenient_issubclass433-434- return lenient_issubclass(type_, tuple) and hasattr(type_, "_fields")435-436-437-def is_typeddict(type_: Type[Any]) -> bool:438- """439- Check if a given class is a typed dict (from `typing` or `typing_extensions`)440- In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict)441- """442- from .utils import lenient_issubclass443-444- return lenient_issubclass(type_, dict) and hasattr(type_, "__total__")445-446-447-test_type = NewType("test_type", str)448-449-450-def is_new_type(type_: Type[Any]) -> bool:451- """452- Check whether type_ was created using typing.NewType453- """454- return isinstance(type_, test_type.__class__) and hasattr(type_, "__supertype__") # type: ignore455-456-457-def new_type_supertype(type_: Type[Any]) -> Type[Any]:458- while hasattr(type_, "__supertype__"):459- type_ = type_.__supertype__460- return type_461-462-463-def _check_classvar(v: Optional[Type[Any]]) -> bool:464- if v is None:465- return False466-467- return v.__class__ == ClassVar.__class__ and getattr(v, "_name", None) == "ClassVar"468-469-470-def is_classvar(ann_type: Type[Any]) -> bool:471- if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)):472- return True473-474- # this is an ugly workaround for class vars that contain forward references and are therefore themselves475- # forward references, see #3679476- if ann_type.__class__ == ForwardRef and ann_type.__forward_arg__.startswith(477- "ClassVar["478- ):479- return True480-481- return False482-483-484-# Only in Pydantic485-# def update_field_forward_refs(field: "ModelField", globalns: Any, localns: Any) -> None:486-# """487-# Try to update ForwardRefs on fields based on this ModelField, globalns and localns.488-# """489-# if field.type_.__class__ == ForwardRef:490-# field.type_ = evaluate_forwardref(field.type_, globalns, localns or None)491-# field.prepare()492-493-# if field.sub_fields:494-# for sub_f in field.sub_fields:495-# update_field_forward_refs(sub_f, globalns=globalns, localns=localns)496-497-# if field.discriminator_key is not None:498-# field.prepare_discriminated_union_sub_fields()499-500-501-# Only in Pydantic502-# def update_model_forward_refs(503-# model: Type[Any],504-# fields: Iterable["ModelField"],505-# json_encoders: Dict[Union[Type[Any], str], AnyCallable],506-# localns: "DictStrAny",507-# exc_to_suppress: Tuple[Type[BaseException], ...] = (),508-# ) -> None:509-# """510-# Try to update model fields ForwardRefs based on model and localns.511-# """512-# if model.__module__ in sys.modules:513-# globalns = sys.modules[model.__module__].__dict__.copy()514-# else:515-# globalns = {}516-517-# globalns.setdefault(model.__name__, model)518-519-# for f in fields:520-# try:521-# update_field_forward_refs(f, globalns=globalns, localns=localns)522-# except exc_to_suppress:523-# pass524-525-# for key in set(json_encoders.keys()):526-# if isinstance(key, str):527-# fr: ForwardRef = ForwardRef(key)528-# elif isinstance(key, ForwardRef):529-# fr = key530-# else:531-# continue532-533-# try:534-# new_key = evaluate_forwardref(fr, globalns, localns or None)535-# except exc_to_suppress: # pragma: no cover536-# continue537-538-# json_encoders[new_key] = json_encoders.pop(key)539-540-541-def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]:542- """543- Tries to get the class of a Type[T] annotation. Returns True if Type is used544- without brackets. Otherwise returns None.545- """546- try:547- origin = get_origin(type_)548- if origin is None: # Python 3.6549- origin = type_550- if issubclass(origin, Type): # type: ignore551- if not get_args(type_) or not isinstance(get_args(type_)[0], type):552- return True553- return get_args(type_)[0]554- except (AttributeError, TypeError):555- pass556- return None557-558-559-def get_sub_types(tp: Any) -> List[Any]:560- """561- Return all the types that are allowed by type `tp`562- `tp` can be a `Union` of allowed types or an `Annotated` type563- """564- origin = get_origin(tp)565- if origin is Annotated:566- return get_sub_types(get_args(tp)[0])567- elif is_union(origin):568- return [x for t in get_args(tp) for x in get_sub_types(t)]569- else:570- return [tp]modified:typer/main.py+2 added-1 removed
10 unmodified lines11 from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union12 from uuid import UUID13 14 import click15+from typing_extensions import get_args, get_origin16 16-from ._typing import get_args, get_origin, is_union17+from ._typing import is_union18 from .completion import get_completion_inspect_parameters19 from .core import (20 DEFAULT_MARKUP_MODE,21 MarkupMode,1060 unmodified linesmodified:typer/utils.py+2 added-3 removed
1 unmodified line2 import sys3 from copy import copy4 from typing import Any, Callable, Dict, List, Tuple, Type, cast5 6-from typing_extensions import Annotated, get_type_hints6+from typing_extensions import Annotated, get_args, get_origin, get_type_hints7 8-from ._typing import get_args, get_origin8 from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta9 10 11 def _param_type_to_user_string(param_type: Type[ParameterInfo]) -> str:82 unmodified lines94 95 def _split_annotation_from_typer_annotations(96 base_annotation: Type[Any],97 ) -> Tuple[Type[Any], List[ParameterInfo]]:99- if get_origin(base_annotation) is not Annotated: # type: ignore98+ if get_origin(base_annotation) is not Annotated:99 return base_annotation, []100 base_annotation, *maybe_typer_annotations = get_args(base_annotation)101 return base_annotation, [102 annotation89 unmodified linesmodified:pyproject.toml-3 removed
192 unmodified lines193 "docs_src/prompt/tutorial003.py" = ["F841"]194 # Loop control variable `x` not used within loop body195 "docs_src/using_click/tutorial001.py" = ["B007"]196 197-# TODO: refactor _typing.py, remove unnecessary code198-"typer/_typing.py" = ["UP036", "F822"]199-197 [tool.ruff.lint.isort]198 known-third-party = ["typer", "click"]199 # For docs_src/subcommands/tutorial003/200 known-first-party = ["reigns", "towns", "lands", "items", "users"]4 unmodified lines