Skip to content
Myr

✨ Add support for custom types and parsers (updates/builds upon PR #443) (#583)

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

* Support custom parameter types While most CLI parameters are strings, ints, etc, we sometimes need custom types. Currently typer has no support for it (See #77), and while there are a few hacks, the likely solution is to add a 'str' argument and parse it inside the main function. This PR adds support for custom types in 3 different ways: - Manually specifying a `click_type` - Manually specifying a `parse` function - Using a Callable type annotation (It is very common for types to have a string constructor, like `int("1")`) * Document how to parse custom objects with Typer. Typer supports parsing of cutom types with: - A user provided parser class - A click custom type parser * 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks * 📝 Tweak and simplify docs * ✅ Tweak tests to run scripts and remove pragma: nocover in examples * 📝 Tweak examples for docs, add types and remove # pragma: nocover * ♻️ Tweak implementation checking for parser and Click type ---------

authored by John Purviance · committed by GitHub · parent 8dd7642 · Browse files · 13 files+522 added−4 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: Paulo Costa <me@paulo.costa.nom.br>
  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

13 files+522 added−4 removed

  • tests:+163 added−2 removed
  • other:+359 added−2 removed

13 files+522 added−4 removed

added:docs/tutorial/parameter-types/custom_types.md+27 added
added:docs_src/parameter_types/custom_types/__init__.py
added:docs_src/parameter_types/custom_types/tutorial001.py+25 added
1import typer234class CustomClass:5 def __init__(self, value: str):6 self.value = value78 def __str__(self):9 return f"<CustomClass: value={self.value}>"101112def parse_custom_class(value: str):13 return CustomClass(value * 2)141516def main(17 custom_arg: CustomClass = typer.Argument("X", parser=parse_custom_class),18 custom_opt: CustomClass = typer.Option("Y", parser=parse_custom_class),19):20 print(f"custom_arg is {custom_arg}")21 print(f"--custom-opt is {custom_opt}")222324if __name__ == "__main__":25 typer.run(main)
added:docs_src/parameter_types/custom_types/tutorial002.py+29 added
1import click2import typer345class CustomClass:6 def __init__(self, value: str):7 self.value = value89 def __repr__(self):10 return f"<CustomClass: value={self.value}>"111213class CustomClassParser(click.ParamType):14 name = "CustomClass"1516 def convert(self, value, param, ctx):17 return CustomClass(value * 3)181920def main(21 custom_arg: CustomClass = typer.Argument("X", click_type=CustomClassParser()),22 custom_opt: CustomClass = typer.Option("Y", click_type=CustomClassParser()),23):24 print(f"custom_arg is {custom_arg}")25 print(f"--custom-opt is {custom_opt}")262728if __name__ == "__main__":29 typer.run(main)
added:tests/test_tutorial/test_parameter_types/test_custom_types/__init__.py
added:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial001.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.custom_types import tutorial001 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 0181920def test_parse_custom_type():21 result = runner.invoke(app, ["0", "--custom-opt", "1"])22 assert "custom_arg is <CustomClass: value=00>" in result.output23 assert "custom-opt is <CustomClass: value=11>" in result.output242526def test_parse_custom_type_with_default():27 result = runner.invoke(app, ["0"])28 assert "custom_arg is <CustomClass: value=00>" in result.output29 assert "custom-opt is <CustomClass: value=YY>" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial002.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.custom_types import tutorial002 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 0181920def test_parse_custom_type():21 result = runner.invoke(app, ["0", "--custom-opt", "1"])22 assert "custom_arg is <CustomClass: value=000>" in result.output23 assert "custom-opt is <CustomClass: value=111>" in result.output242526def test_parse_custom_type_with_default():27 result = runner.invoke(app, ["0"])28 assert "custom_arg is <CustomClass: value=000>" in result.output29 assert "custom-opt is <CustomClass: value=YYY>" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
modified:tests/test_others.py+46 added-1 removed
1import os2import subprocess3import sys4import typing5from pathlib import Path6from unittest import mock78import click
1 unmodified line
10import shellingham11import typer12import typer.completion13from typer.main import solve_typer_info_defaults, solve_typer_info_help13from typer.models import TyperInfo14from typer.models import ParameterInfo, TyperInfo15from typer.testing import CliRunner1617runner = CliRunner()18
9 unmodified lines
28 value = solve_typer_info_defaults(TyperInfo())29 assert value303132def test_too_may_parsers():33 def custom_parser(value: str) -> int:34 return int(value) # pragma: no cover3536 class CustomClickParser(click.ParamType):37 name = "custom_parser"3839 def convert(40 self,41 value: str,42 param: typing.Optional[click.Parameter],43 ctx: typing.Optional[click.Context],44 ) -> typing.Any:45 return int(value) # pragma: no cover4647 expected_error = (48 "Multiple custom type parsers provided. "49 "`parser` and `click_type` may not both be provided."50 )5152 with pytest.raises(ValueError, match=expected_error):53 ParameterInfo(parser=custom_parser, click_type=CustomClickParser())545556def test_valid_parser_permutations():57 def custom_parser(value: str) -> int:58 return int(value) # pragma: no cover5960 class CustomClickParser(click.ParamType):61 name = "custom_parser"6263 def convert(64 self,65 value: str,66 param: typing.Optional[click.Parameter],67 ctx: typing.Optional[click.Context],68 ) -> typing.Any:69 return int(value) # pragma: no cover7071 ParameterInfo()72 ParameterInfo(parser=custom_parser)73 ParameterInfo(click_type=CustomClickParser())747576def test_install_invalid_shell():77 app = typer.Typer()7879 @app.command()
178 unmodified lines
modified:tests/test_type_conversion.py+39 added-1 removed
1from enum import Enum2from pathlib import Path3from typing import List, Optional, Tuple3from typing import Any, List, Optional, Tuple45import click6import pytest7import typer8from typer.testing import CliRunner9
80 unmodified lines
90 assert isinstance(element, expected_type)9192 result = runner.invoke(app, ["one", "two"])93 assert result.exit_code == 0949596def test_custom_parse():97 app = typer.Typer()9899 @app.command()100 def custom_parser(101 hex_value: int = typer.Argument(None, parser=lambda x: int(x, 0))102 ):103 assert hex_value == 0x56104105 result = runner.invoke(app, ["0x56"])106 assert result.exit_code == 0107108109def test_custom_click_type():110 class BaseNumberParamType(click.ParamType):111 name = "base_integer"112113 def convert(114 self,115 value: Any,116 param: Optional[click.Parameter],117 ctx: Optional[click.Context],118 ) -> Any:119 return int(value, 0)120121 app = typer.Typer()122123 @app.command()124 def custom_click_type(125 hex_value: int = typer.Argument(None, click_type=BaseNumberParamType())126 ):127 assert hex_value == 0x56128129 result = runner.invoke(app, ["0x56"])130 assert result.exit_code == 0
modified:typer/main.py+7 added-1 removed
687 unmodified lines
688689def get_click_type(690 *, annotation: Any, parameter_info: ParameterInfo691) -> click.ParamType:692 if parameter_info.click_type is not None:693 return parameter_info.click_type694695 elif parameter_info.parser is not None:696 return click.types.FuncParamType(parameter_info.parser)697692 if annotation == str:698 elif annotation == str:699 return click.STRING700 elif annotation == int:701 if parameter_info.min is not None or parameter_info.max is not None:702 min_ = None
354 unmodified lines
modified:typer/models.py+25 added
182 unmodified lines
183 Union[List["click.shell_completion.CompletionItem"], List[str]],184 ]185 ] = None,186 autocompletion: Optional[Callable[..., Any]] = None,187 # Custom type188 parser: Optional[Callable[[str], Any]] = None,189 click_type: Optional[click.ParamType] = None,190 # TyperArgument191 show_default: Union[bool, str] = True,192 show_choices: bool = True,193 show_envvar: bool = True,
24 unmodified lines
218 path_type: Union[None, Type[str], Type[bytes]] = None,219 # Rich settings220 rich_help_panel: Union[str, None] = None,221 ):222 # Check if user has provided multiple custom parsers223 if parser and click_type:224 raise ValueError(225 "Multiple custom type parsers provided. "226 "`parser` and `click_type` may not both be provided."227 )228229 self.default = default230 self.param_decls = param_decls231 self.callback = callback232 self.metavar = metavar
1 unmodified line
234 self.is_eager = is_eager235 self.envvar = envvar236 self.shell_complete = shell_complete237 self.autocompletion = autocompletion238 # Custom type239 self.parser = parser240 self.click_type = click_type241 # TyperArgument242 self.show_default = show_default243 self.show_choices = show_choices244 self.show_envvar = show_envvar
44 unmodified lines
289 Union[List["click.shell_completion.CompletionItem"], List[str]],290 ]291 ] = None,292 autocompletion: Optional[Callable[..., Any]] = None,293 # Custom type294 parser: Optional[Callable[[str], Any]] = None,295 click_type: Optional[click.ParamType] = None,296 # Option297 show_default: bool = True,298 prompt: Union[bool, str] = False,299 confirmation_prompt: bool = False,
42 unmodified lines
342 is_eager=is_eager,343 envvar=envvar,344 shell_complete=shell_complete,345 autocompletion=autocompletion,346 # Custom type347 parser=parser,348 click_type=click_type,349 # TyperArgument350 show_default=show_default,351 show_choices=show_choices,352 show_envvar=show_envvar,
53 unmodified lines
406 Union[List["click.shell_completion.CompletionItem"], List[str]],407 ]408 ] = None,409 autocompletion: Optional[Callable[..., Any]] = None,410 # Custom type411 parser: Optional[Callable[[str], Any]] = None,412 click_type: Optional[click.ParamType] = None,413 # TyperArgument414 show_default: Union[bool, str] = True,415 show_choices: bool = True,416 show_envvar: bool = True,
34 unmodified lines
451 is_eager=is_eager,452 envvar=envvar,453 shell_complete=shell_complete,454 autocompletion=autocompletion,455 # Custom type456 parser=parser,457 click_type=click_type,458 # TyperArgument459 show_default=show_default,460 show_choices=show_choices,461 show_envvar=show_envvar,
56 unmodified lines
modified:typer/params.py+245 added-1 removed
1from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union1from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, overload23import click45from .models import ArgumentInfo, OptionInfo
1 unmodified line
7if TYPE_CHECKING: # pragma: no cover8 import click.shell_completion91011@overload12def Option(13 # Parameter14 default: Optional[Any],15 *param_decls: str,
8 unmodified lines
24 Union[List["click.shell_completion.CompletionItem"], List[str]],25 ]26 ] = None,27 autocompletion: Optional[Callable[..., Any]] = None,28 # Custom type29 parser: Optional[Callable[[str], Any]] = None,30 # Option31 show_default: bool = True,32 prompt: Union[bool, str] = False,33 confirmation_prompt: bool = False,
32 unmodified lines
66 path_type: Union[None, Type[str], Type[bytes]] = None,67 # Rich settings68 rich_help_panel: Union[str, None] = None,69) -> Any:70 ...717273@overload74def Option(75 # Parameter76 default: Optional[Any],77 *param_decls: str,78 callback: Optional[Callable[..., Any]] = None,79 metavar: Optional[str] = None,80 expose_value: bool = True,81 is_eager: bool = False,82 envvar: Optional[Union[str, List[str]]] = None,83 shell_complete: Optional[84 Callable[85 [click.Context, click.Parameter, str],86 Union[List["click.shell_completion.CompletionItem"], List[str]],87 ]88 ] = None,89 autocompletion: Optional[Callable[..., Any]] = None,90 # Custom type91 click_type: Optional[click.ParamType] = None,92 # Option93 show_default: bool = True,94 prompt: Union[bool, str] = False,95 confirmation_prompt: bool = False,96 prompt_required: bool = True,97 hide_input: bool = False,98 is_flag: Optional[bool] = None,99 flag_value: Optional[Any] = None,100 count: bool = False,101 allow_from_autoenv: bool = True,102 help: Optional[str] = None,103 hidden: bool = False,104 show_choices: bool = True,105 show_envvar: bool = True,106 # Choice107 case_sensitive: bool = True,108 # Numbers109 min: Optional[Union[int, float]] = None,110 max: Optional[Union[int, float]] = None,111 clamp: bool = False,112 # DateTime113 formats: Optional[List[str]] = None,114 # File115 mode: Optional[str] = None,116 encoding: Optional[str] = None,117 errors: Optional[str] = "strict",118 lazy: Optional[bool] = None,119 atomic: bool = False,120 # Path121 exists: bool = False,122 file_okay: bool = True,123 dir_okay: bool = True,124 writable: bool = False,125 readable: bool = True,126 resolve_path: bool = False,127 allow_dash: bool = False,128 path_type: Union[None, Type[str], Type[bytes]] = None,129 # Rich settings130 rich_help_panel: Union[str, None] = None,131) -> Any:132 ...133134135def Option(136 # Parameter137 default: Optional[Any],138 *param_decls: str,139 callback: Optional[Callable[..., Any]] = None,140 metavar: Optional[str] = None,141 expose_value: bool = True,142 is_eager: bool = False,143 envvar: Optional[Union[str, List[str]]] = None,144 shell_complete: Optional[145 Callable[146 [click.Context, click.Parameter, str],147 Union[List["click.shell_completion.CompletionItem"], List[str]],148 ]149 ] = None,150 autocompletion: Optional[Callable[..., Any]] = None,151 # Custom type152 parser: Optional[Callable[[str], Any]] = None,153 click_type: Optional[click.ParamType] = None,154 # Option155 show_default: bool = True,156 prompt: Union[bool, str] = False,157 confirmation_prompt: bool = False,158 prompt_required: bool = True,159 hide_input: bool = False,160 is_flag: Optional[bool] = None,161 flag_value: Optional[Any] = None,162 count: bool = False,163 allow_from_autoenv: bool = True,164 help: Optional[str] = None,165 hidden: bool = False,166 show_choices: bool = True,167 show_envvar: bool = True,168 # Choice169 case_sensitive: bool = True,170 # Numbers171 min: Optional[Union[int, float]] = None,172 max: Optional[Union[int, float]] = None,173 clamp: bool = False,174 # DateTime175 formats: Optional[List[str]] = None,176 # File177 mode: Optional[str] = None,178 encoding: Optional[str] = None,179 errors: Optional[str] = "strict",180 lazy: Optional[bool] = None,181 atomic: bool = False,182 # Path183 exists: bool = False,184 file_okay: bool = True,185 dir_okay: bool = True,186 writable: bool = False,187 readable: bool = True,188 resolve_path: bool = False,189 allow_dash: bool = False,190 path_type: Union[None, Type[str], Type[bytes]] = None,191 # Rich settings192 rich_help_panel: Union[str, None] = None,193) -> Any:194 return OptionInfo(195 # Parameter196 default=default,197 param_decls=param_decls,
3 unmodified lines
201 is_eager=is_eager,202 envvar=envvar,203 shell_complete=shell_complete,204 autocompletion=autocompletion,205 # Custom type206 parser=parser,207 click_type=click_type,208 # Option209 show_default=show_default,210 prompt=prompt,211 confirmation_prompt=confirmation_prompt,
34 unmodified lines
246 rich_help_panel=rich_help_panel,247 )248249250@overload251def Argument(252 # Parameter253 default: Optional[Any],254 *,
8 unmodified lines
263 Union[List["click.shell_completion.CompletionItem"], List[str]],264 ]265 ] = None,266 autocompletion: Optional[Callable[..., Any]] = None,267 # Custom type268 parser: Optional[Callable[[str], Any]] = None,269 # TyperArgument270 show_default: Union[bool, str] = True,271 show_choices: bool = True,272 show_envvar: bool = True,
24 unmodified lines
297 path_type: Union[None, Type[str], Type[bytes]] = None,298 # Rich settings299 rich_help_panel: Union[str, None] = None,300) -> Any:301 ...302303304@overload305def Argument(306 # Parameter307 default: Optional[Any],308 *,309 callback: Optional[Callable[..., Any]] = None,310 metavar: Optional[str] = None,311 expose_value: bool = True,312 is_eager: bool = False,313 envvar: Optional[Union[str, List[str]]] = None,314 shell_complete: Optional[315 Callable[316 [click.Context, click.Parameter, str],317 Union[List["click.shell_completion.CompletionItem"], List[str]],318 ]319 ] = None,320 autocompletion: Optional[Callable[..., Any]] = None,321 # Custom type322 click_type: Optional[click.ParamType] = None,323 # TyperArgument324 show_default: Union[bool, str] = True,325 show_choices: bool = True,326 show_envvar: bool = True,327 help: Optional[str] = None,328 hidden: bool = False,329 # Choice330 case_sensitive: bool = True,331 # Numbers332 min: Optional[Union[int, float]] = None,333 max: Optional[Union[int, float]] = None,334 clamp: bool = False,335 # DateTime336 formats: Optional[List[str]] = None,337 # File338 mode: Optional[str] = None,339 encoding: Optional[str] = None,340 errors: Optional[str] = "strict",341 lazy: Optional[bool] = None,342 atomic: bool = False,343 # Path344 exists: bool = False,345 file_okay: bool = True,346 dir_okay: bool = True,347 writable: bool = False,348 readable: bool = True,349 resolve_path: bool = False,350 allow_dash: bool = False,351 path_type: Union[None, Type[str], Type[bytes]] = None,352 # Rich settings353 rich_help_panel: Union[str, None] = None,354) -> Any:355 ...356357358def Argument(359 # Parameter360 default: Optional[Any],361 *,362 callback: Optional[Callable[..., Any]] = None,363 metavar: Optional[str] = None,364 expose_value: bool = True,365 is_eager: bool = False,366 envvar: Optional[Union[str, List[str]]] = None,367 shell_complete: Optional[368 Callable[369 [click.Context, click.Parameter, str],370 Union[List["click.shell_completion.CompletionItem"], List[str]],371 ]372 ] = None,373 autocompletion: Optional[Callable[..., Any]] = None,374 # Custom type375 parser: Optional[Callable[[str], Any]] = None,376 click_type: Optional[click.ParamType] = None,377 # TyperArgument378 show_default: Union[bool, str] = True,379 show_choices: bool = True,380 show_envvar: bool = True,381 help: Optional[str] = None,382 hidden: bool = False,383 # Choice384 case_sensitive: bool = True,385 # Numbers386 min: Optional[Union[int, float]] = None,387 max: Optional[Union[int, float]] = None,388 clamp: bool = False,389 # DateTime390 formats: Optional[List[str]] = None,391 # File392 mode: Optional[str] = None,393 encoding: Optional[str] = None,394 errors: Optional[str] = "strict",395 lazy: Optional[bool] = None,396 atomic: bool = False,397 # Path398 exists: bool = False,399 file_okay: bool = True,400 dir_okay: bool = True,401 writable: bool = False,402 readable: bool = True,403 resolve_path: bool = False,404 allow_dash: bool = False,405 path_type: Union[None, Type[str], Type[bytes]] = None,406 # Rich settings407 rich_help_panel: Union[str, None] = None,408) -> Any:409 return ArgumentInfo(410 # Parameter411 default=default,412 # Arguments can only have one param declaration
5 unmodified lines
418 is_eager=is_eager,419 envvar=envvar,420 shell_complete=shell_complete,421 autocompletion=autocompletion,422 # Custom type423 parser=parser,424 click_type=click_type,425 # TyperArgument426 show_default=show_default,427 show_choices=show_choices,428 show_envvar=show_envvar,
28 unmodified lines
modified:mkdocs.yml+1 added
58 unmodified lines
59 - DateTime: tutorial/parameter-types/datetime.md60 - Enum - Choices: tutorial/parameter-types/enum.md61 - Path: tutorial/parameter-types/path.md62 - File: tutorial/parameter-types/file.md63 - Custom Types: tutorial/parameter-types/custom_types.md64 - SubCommands - Command Groups:65 - SubCommands - Command Groups - Intro: tutorial/subcommands/index.md66 - Add Typer: tutorial/subcommands/add-typer.md67 - SubCommands in a Single File: tutorial/subcommands/single-file.md
66 unmodified lines