Skip to content
Myr

utils.py

This file

Path

typer/utils.py

192 lines · 7.2 KiB · Python

Last changed by

🐛 Fix evaluating stringified annotations in Python 3.10 (also `from __future__ import annotations`) (#721)Kazantcev Andreybefore adoptiond1a177c

History of this file

Take it

1import inspect2import sys3from copy import copy4from typing import Any, Callable, Dict, List, Tuple, Type, cast, get_type_hints56from typing_extensions import Annotated78from ._typing import get_args, get_origin9from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta101112def _param_type_to_user_string(param_type: Type[ParameterInfo]) -> str:13    # Render a `ParameterInfo` subclass for use in error messages.14    # User code doesn't call `*Info` directly, so errors should present the classes how15    # they were (probably) defined in the user code.16    if param_type is OptionInfo:17        return "`Option`"18    elif param_type is ArgumentInfo:19        return "`Argument`"20    # This line shouldn't be reachable during normal use.21    return f"`{param_type.__name__}`"  # pragma: no cover222324class AnnotatedParamWithDefaultValueError(Exception):25    argument_name: str26    param_type: Type[ParameterInfo]2728    def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):29        self.argument_name = argument_name30        self.param_type = param_type3132    def __str__(self) -> str:33        param_type_str = _param_type_to_user_string(self.param_type)34        return (35            f"{param_type_str} default value cannot be set in `Annotated`"36            f" for {self.argument_name!r}. Set the default value with `=` instead."37        )383940class MixedAnnotatedAndDefaultStyleError(Exception):41    argument_name: str42    annotated_param_type: Type[ParameterInfo]43    default_param_type: Type[ParameterInfo]4445    def __init__(46        self,47        argument_name: str,48        annotated_param_type: Type[ParameterInfo],49        default_param_type: Type[ParameterInfo],50    ):51        self.argument_name = argument_name52        self.annotated_param_type = annotated_param_type53        self.default_param_type = default_param_type5455    def __str__(self) -> str:56        annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)57        default_param_type_str = _param_type_to_user_string(self.default_param_type)58        msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"59        if self.annotated_param_type is self.default_param_type:60            msg += " default value"61        else:62            msg += f" {default_param_type_str} as a default value"63        msg += f" together for {self.argument_name!r}"64        return msg656667class MultipleTyperAnnotationsError(Exception):68    argument_name: str6970    def __init__(self, argument_name: str):71        self.argument_name = argument_name7273    def __str__(self) -> str:74        return (75            "Cannot specify multiple `Annotated` Typer arguments"76            f" for {self.argument_name!r}"77        )787980class DefaultFactoryAndDefaultValueError(Exception):81    argument_name: str82    param_type: Type[ParameterInfo]8384    def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):85        self.argument_name = argument_name86        self.param_type = param_type8788    def __str__(self) -> str:89        param_type_str = _param_type_to_user_string(self.param_type)90        return (91            "Cannot specify `default_factory` and a default value together"92            f" for {param_type_str}"93        )949596def _split_annotation_from_typer_annotations(97    base_annotation: Type[Any],98) -> Tuple[Type[Any], List[ParameterInfo]]:99    if get_origin(base_annotation) is not Annotated:  # type: ignore100        return base_annotation, []101    base_annotation, *maybe_typer_annotations = get_args(base_annotation)102    return base_annotation, [103        annotation104        for annotation in maybe_typer_annotations105        if isinstance(annotation, ParameterInfo)106    ]107108109def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:110    if sys.version_info >= (3, 10):111        signature = inspect.signature(func, eval_str=True)112    else:113        signature = inspect.signature(func)114115    type_hints = get_type_hints(func)116    params = {}117    for param in signature.parameters.values():118        annotation, typer_annotations = _split_annotation_from_typer_annotations(119            param.annotation,120        )121        if len(typer_annotations) > 1:122            raise MultipleTyperAnnotationsError(param.name)123124        default = param.default125        if typer_annotations:126            # It's something like `my_param: Annotated[str, Argument()]`127            [parameter_info] = typer_annotations128129            # Forbid `my_param: Annotated[str, Argument()] = Argument("...")`130            if isinstance(param.default, ParameterInfo):131                raise MixedAnnotatedAndDefaultStyleError(132                    argument_name=param.name,133                    annotated_param_type=type(parameter_info),134                    default_param_type=type(param.default),135                )136137            parameter_info = copy(parameter_info)138139            # When used as a default, `Option` takes a default value and option names140            # as positional arguments:141            #   `Option(some_value, "--some-argument", "-s")`142            # When used in `Annotated` (ie, what this is handling), `Option` just takes143            # option names as positional arguments:144            #   `Option("--some-argument", "-s")`145            # In this case, the `default` attribute of `parameter_info` is actually146            # meant to be the first item of `param_decls`.147            if (148                isinstance(parameter_info, OptionInfo)149                and parameter_info.default is not ...150            ):151                parameter_info.param_decls = (152                    cast(str, parameter_info.default),153                    *(parameter_info.param_decls or ()),154                )155                parameter_info.default = ...156157            # Forbid `my_param: Annotated[str, Argument('some-default')]`158            if parameter_info.default is not ...:159                raise AnnotatedParamWithDefaultValueError(160                    param_type=type(parameter_info),161                    argument_name=param.name,162                )163            if param.default is not param.empty:164                # Put the parameter's default (set by `=`) into `parameter_info`, where165                # typer can find it.166                parameter_info.default = param.default167168            default = parameter_info169        elif param.name in type_hints:170            # Resolve forward references.171            annotation = type_hints[param.name]172173        if isinstance(default, ParameterInfo):174            parameter_info = copy(default)175            # Click supports `default` as either176            # - an actual value; or177            # - a factory function (returning a default value.)178            # The two are not interchangeable for static typing, so typer allows179            # specifying `default_factory`. Move the `default_factory` into `default`180            # so click can find it.181            if parameter_info.default is ... and parameter_info.default_factory:182                parameter_info.default = parameter_info.default_factory183            elif parameter_info.default_factory:184                raise DefaultFactoryAndDefaultValueError(185                    argument_name=param.name, param_type=type(parameter_info)186                )187            default = parameter_info188189        params[param.name] = ParamMeta(190            name=param.name, default=default, annotation=annotation191        )192    return params