Skip to content
Myr

:sparkles: Add support for forward references (#93)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* :sparkles: Add support for forward references * :white_check_mark: Add forward references test * :bug: Fix coverage in completion * :bug: Fix testing with Pytest and Pytest-sugar * :pushpin: Pin Pytest

authored by Sebastián Ramírez · committed by GitHub · parent deda63a · Browse files · 6 files+79 added−17 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+79 added−17 removed

  • tests:+23 added−0 removed
  • other:+56 added−17 removed

6 files+79 added−17 removed

modified:tests/test_others.py+23 added
197 unmodified lines
198199 with pytest.raises(click.ClickException) as exc_info:200 runner.invoke(app, ["--name", "Camila"])201 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"202203204def test_forward_references():205 app = typer.Typer()206207 @app.command()208 def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):209 typer.echo(f"arg1: {type(arg1)} {arg1}")210 typer.echo(f"arg2: {type(arg2)} {arg2}")211 typer.echo(f"arg3: {type(arg3)} {arg3}")212 typer.echo(f"arg4: {type(arg4)} {arg4}")213 typer.echo(f"arg5: {type(arg5)} {arg5}")214215 result = runner.invoke(app, ["Hello", "2", "invalid"])216 assert (217 "Error: Invalid value for 'ARG3': invalid is not a valid integer"218 in result.stdout219 )220 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])221 assert (222 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"223 in result.stdout224 )
modified:typer/completion.py+10 added-7 removed
1import inspect1import os2import re3import subprocess4import sys
3 unmodified lines
89import click10import click._bashcomplete1112from .models import ParamMeta13from .params import Option14from .utils import get_params_from_function1516try:17 import shellingham18except ImportError: # pragma: nocover
2 unmodified lines
2122_click_patched = False232424def get_completion_inspect_parameters() -> Tuple[inspect.Parameter, inspect.Parameter]:25def get_completion_inspect_parameters() -> Tuple[ParamMeta, ParamMeta]:26 completion_init()27 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")28 if shellingham and not test_disable_detection:28 signature = inspect.signature(_install_completion_placeholder_function)29 parameters = get_params_from_function(_install_completion_placeholder_function)30 else:30 signature = inspect.signature(_install_completion_no_auto_placeholder_function)31 install_param, show_param = signature.parameters.values()31 parameters = get_params_from_function(32 _install_completion_no_auto_placeholder_function33 )34 install_param, show_param = parameters.values()35 return install_param, show_param363738def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
167 unmodified lines
206 if rc_path.is_file():207 rc_content = rc_path.read_text()208 completion_init_lines = [f"source {completion_path}"]209 for line in completion_init_lines:207 if line not in rc_content:210 if line not in rc_content: # pragma: nocover211 rc_content += f"\n{line}"212 rc_content += "\n"213 rc_path.write_text(rc_content)214 # Install completion
18 unmodified lines
233 "zstyle ':completion:*' menu select",234 "fpath+=~/.zfunc",235 ]236 for line in completion_init_lines:234 if line not in zshrc_content:237 if line not in zshrc_content: # pragma: nocover238 zshrc_content += f"\n{line}"239 zshrc_content += "\n"240 zshrc_path.write_text(zshrc_content)241 # Install completion under ~/.zfunc/
228 unmodified lines
modified:typer/main.py+11 added-9 removed
21 unmodified lines
22 FileTextWrite,23 NoneType,24 OptionInfo,25 ParameterInfo,26 ParamMeta,27 Required,28 TyperInfo,29)30from .utils import get_params_from_function313233def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:34 install_param, show_param = get_completion_inspect_parameters()
359 unmodified lines
394 params = []395 convertors = {}396 context_param_name = None397 if callback:396 signature = inspect.signature(callback)397 for param_name, param in signature.parameters.items():398 parameters = get_params_from_function(callback)399 for param_name, param in parameters.items():400 if lenient_issubclass(param.annotation, click.Context):401 context_param_name = param_name402 continue403 click_param, convertor = get_click_param(param)
73 unmodified lines
477 context_param_name: str = None,478) -> Optional[Callable]:479 if not callback:480 return None479 signature = inspect.signature(callback)481 parameters = get_params_from_function(callback)482 use_params: Dict[str, Any] = {}481 for param_name, param_sig in signature.parameters.items():483 for param_name in parameters:484 use_params[param_name] = None485 for param in params:486 use_params[param.name] = param.default487
104 unmodified lines
592 return isinstance(cls, type) and issubclass(cls, class_or_tuple)593594595def get_click_param(594 param: inspect.Parameter,596 param: ParamMeta,597) -> Tuple[Union[click.Argument, click.Option], Any]:598 # First, find out what will be:599 # * ParamInfo (ArgumentInfo or OptionInfo)600 # * default_value
144 unmodified lines
745 *, callback: Optional[Callable] = None, convertor: Optional[Callable] = None746) -> Optional[Callable]:747 if not callback:748 return None747 signature = inspect.signature(callback)749 parameters = get_params_from_function(callback)750 ctx_name = None751 click_param_name = None752 value_name = None753 untyped_names: List[str] = []752 for param_name, param_sig in signature.parameters.items():754 for param_name, param_sig in parameters.items():755 if lenient_issubclass(param_sig.annotation, click.Context):756 ctx_name = param_name757 elif lenient_issubclass(param_sig.annotation, click.Parameter):758 click_param_name = param_name
34 unmodified lines
793794def get_param_completion(callback: Optional[Callable] = None) -> Optional[Callable]:795 if not callback:796 return None795 signature = inspect.signature(callback)797 parameters = get_params_from_function(callback)798 ctx_name = None799 args_name = None800 incomplete_name = None799 unassigned_params = [param for param in signature.parameters.values()]801 unassigned_params = [param for param in parameters.values()]802 for param_sig in unassigned_params[:]:803 origin = getattr(param_sig.annotation, "__origin__", None)804 if lenient_issubclass(param_sig.annotation, click.Context):805 ctx_name = param_sig.name
43 unmodified lines
modified:typer/models.py+16 added
1import inspect2import io3from typing import (4 TYPE_CHECKING,5 Any,
382 unmodified lines
388 resolve_path=resolve_path,389 allow_dash=allow_dash,390 path_type=path_type,391 )392393394class ParamMeta:395 empty = inspect.Parameter.empty396397 def __init__(398 self,399 *,400 name: str,401 default: Any = inspect.Parameter.empty,402 annotation: Any = inspect.Parameter.empty,403 ) -> None:404 self.name = name405 self.default = default406 self.annotation = annotation
added:typer/utils.py+18 added
1import inspect2from typing import Callable, Dict, get_type_hints34from .models import ParamMeta567def get_params_from_function(func: Callable) -> Dict[str, ParamMeta]:8 signature = inspect.signature(func)9 type_hints = get_type_hints(func)10 params = {}11 for param in signature.parameters.values():12 annotation = param.annotation13 if param.name in type_hints:14 annotation = type_hints[param.name]15 params[param.name] = ParamMeta(16 name=param.name, default=param.default, annotation=annotation17 )18 return params
modified:pyproject.toml+1 added-1 removed