Skip to content
Myr

utils.py

This file

Path

typer/utils.py

197 lines 路 7.4 KiB 路 Python

Last changed by

Not known.

History of this file

Take it

1import inspect2from collections.abc import Callable3from copy import copy4from typing import Any, cast56from ._typing import Annotated, get_args, get_origin, get_type_hints7from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta8910def _param_type_to_user_string(param_type: type[ParameterInfo]) -> str:11    # Render a `ParameterInfo` subclass for use in error messages.12    # User code doesn't call `*Info` directly, so errors should present the classes how13    # they were (probably) defined in the user code.14    if param_type is OptionInfo:15        return "`Option`"16    elif param_type is ArgumentInfo:17        return "`Argument`"18    # This line shouldn't be reachable during normal use.19    return f"`{param_type.__name__}`"  # pragma: no cover202122class AnnotatedParamWithDefaultValueError(Exception):23    argument_name: str24    param_type: type[ParameterInfo]2526    def __init__(self, argument_name: str, param_type: type[ParameterInfo]):27        self.argument_name = argument_name28        self.param_type = param_type2930    def __str__(self) -> str:31        param_type_str = _param_type_to_user_string(self.param_type)32        return (33            f"{param_type_str} default value cannot be set in `Annotated`"34            f" for {self.argument_name!r}. Set the default value with `=` instead."35        )363738class MixedAnnotatedAndDefaultStyleError(Exception):39    argument_name: str40    annotated_param_type: type[ParameterInfo]41    default_param_type: type[ParameterInfo]4243    def __init__(44        self,45        argument_name: str,46        annotated_param_type: type[ParameterInfo],47        default_param_type: type[ParameterInfo],48    ):49        self.argument_name = argument_name50        self.annotated_param_type = annotated_param_type51        self.default_param_type = default_param_type5253    def __str__(self) -> str:54        annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)55        default_param_type_str = _param_type_to_user_string(self.default_param_type)56        msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"57        if self.annotated_param_type is self.default_param_type:58            msg += " default value"59        else:60            msg += f" {default_param_type_str} as a default value"61        msg += f" together for {self.argument_name!r}"62        return msg636465class MultipleTyperAnnotationsError(Exception):66    argument_name: str6768    def __init__(self, argument_name: str):69        self.argument_name = argument_name7071    def __str__(self) -> str:72        return (73            "Cannot specify multiple `Annotated` Typer arguments"74            f" for {self.argument_name!r}"75        )767778class DefaultFactoryAndDefaultValueError(Exception):79    argument_name: str80    param_type: type[ParameterInfo]8182    def __init__(self, argument_name: str, param_type: type[ParameterInfo]):83        self.argument_name = argument_name84        self.param_type = param_type8586    def __str__(self) -> str:87        param_type_str = _param_type_to_user_string(self.param_type)88        return (89            "Cannot specify `default_factory` and a default value together"90            f" for {param_type_str}"91        )929394def _split_annotation_from_typer_annotations(95    base_annotation: type[Any],96) -> tuple[type[Any], list[ParameterInfo]]:97    if get_origin(base_annotation) is not Annotated:98        return base_annotation, []99    base_annotation, *maybe_typer_annotations = get_args(base_annotation)100    return base_annotation, [101        annotation102        for annotation in maybe_typer_annotations103        if isinstance(annotation, ParameterInfo)104    ]105106107def get_params_from_function(func: Callable[..., Any]) -> dict[str, ParamMeta]:108    signature = inspect.signature(func, eval_str=True)109    type_hints = get_type_hints(func)110    params = {}111    for param in signature.parameters.values():112        annotation, typer_annotations = _split_annotation_from_typer_annotations(113            param.annotation,114        )115        if len(typer_annotations) > 1:116            raise MultipleTyperAnnotationsError(param.name)117118        default = param.default119        if typer_annotations:120            # It's something like `my_param: Annotated[str, Argument()]`121            [parameter_info] = typer_annotations122123            # Forbid `my_param: Annotated[str, Argument()] = Argument("...")`124            if isinstance(param.default, ParameterInfo):125                raise MixedAnnotatedAndDefaultStyleError(126                    argument_name=param.name,127                    annotated_param_type=type(parameter_info),128                    default_param_type=type(param.default),129                )130131            parameter_info = copy(parameter_info)132133            # When used as a default, `Option` takes a default value and option names134            # as positional arguments:135            #   `Option(some_value, "--some-argument", "-s")`136            # When used in `Annotated` (ie, what this is handling), `Option` just takes137            # option names as positional arguments:138            #   `Option("--some-argument", "-s")`139            # In this case, the `default` attribute of `parameter_info` is actually140            # meant to be the first item of `param_decls`.141            if (142                isinstance(parameter_info, OptionInfo)143                and parameter_info.default is not ...144            ):145                parameter_info.param_decls = (146                    cast(str, parameter_info.default),147                    *(parameter_info.param_decls or ()),148                )149                parameter_info.default = ...150151            # Forbid `my_param: Annotated[str, Argument('some-default')]`152            if parameter_info.default is not ...:153                raise AnnotatedParamWithDefaultValueError(154                    param_type=type(parameter_info),155                    argument_name=param.name,156                )157            if param.default is not param.empty:158                # Put the parameter's default (set by `=`) into `parameter_info`, where159                # typer can find it.160                parameter_info.default = param.default161162            default = parameter_info163        elif param.name in type_hints:164            # Resolve forward references.165            annotation = type_hints[param.name]166167        if isinstance(default, ParameterInfo):168            parameter_info = copy(default)169            # Click supports `default` as either170            # - an actual value; or171            # - a factory function (returning a default value.)172            # The two are not interchangeable for static typing, so typer allows173            # specifying `default_factory`. Move the `default_factory` into `default`174            # so click can find it.175            if parameter_info.default is ... and parameter_info.default_factory:176                parameter_info.default = parameter_info.default_factory177            elif parameter_info.default_factory:178                raise DefaultFactoryAndDefaultValueError(179                    argument_name=param.name, param_type=type(parameter_info)180                )181            default = parameter_info182183        params[param.name] = ParamMeta(184            name=param.name, default=default, annotation=annotation185        )186    return params187188189def parse_boolean_env_var(env_var_value: str | None, default: bool) -> bool:190    if env_var_value is None:191        return default192    value = env_var_value.lower()193    if value in ("y", "yes", "t", "true", "on", "1"):194        return True195    if value in ("n", "no", "f", "false", "off", "0"):196        return False197    return default