: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
Provenance
- Commit
a93e6b2- Tree
6c9987d- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
deda63a
6 files changed+79 added−17 removed
modified:tests/test_others.py+23 added
197 unmodified lines198 199 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"202+203+204+def test_forward_references():205+ app = typer.Typer()206+207+ @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}")214+215+ 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
1-import inspect1 import os2 import re3 import subprocess4 import sys3 unmodified lines8 9 import click10 import click._bashcomplete11 12+from .models import ParamMeta13 from .params import Option14+from .utils import get_params_from_function15 16 try:17 import shellingham18 except ImportError: # pragma: nocover2 unmodified lines21 22 _click_patched = False23 24 24-def get_completion_inspect_parameters() -> Tuple[inspect.Parameter, inspect.Parameter]:25+def 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_param36 37 38 def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:167 unmodified lines206 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 completion18 unmodified lines233 "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 linesmodified:typer/main.py+11 added-9 removed
21 unmodified lines22 FileTextWrite,23 NoneType,24 OptionInfo,25 ParameterInfo,26+ ParamMeta,27 Required,28 TyperInfo,29 )30+from .utils import get_params_from_function31 32 33 def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:34 install_param, show_param = get_completion_inspect_parameters()359 unmodified lines394 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 lines477 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 lines592 return isinstance(cls, type) and issubclass(cls, class_or_tuple)593 594 595 def 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_value144 unmodified lines745 *, 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_name34 unmodified lines793 794 def 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.name43 unmodified linesmodified:typer/models.py+16 added
1+import inspect2 import io3 from typing import (4 TYPE_CHECKING,5 Any,382 unmodified lines388 resolve_path=resolve_path,389 allow_dash=allow_dash,390 path_type=path_type,391 )392+393+394+class ParamMeta:395+ empty = inspect.Parameter.empty396+397+ 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 = annotationadded:typer/utils.py+18 added
1+import inspect2+from typing import Callable, Dict, get_type_hints3+4+from .models import ParamMeta5+6+7+def 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 paramsmodified:pyproject.toml+1 added-1 removed
36 unmodified lines3738394041414243444517 unmodified lines36 unmodified lines
[tool.flit.metadata.requires-extra]test = [ "shellingham", "pytest >=4.4.0", "pytest >=4.4.0,< 5.4", "pytest-cov", "coverage", "pytest-xdist", "pytest-sugar",17 unmodified lines