✨ 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 ---------
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
Provenance
- Commit
3e37e01- Tree
27b1c0c- Author
John Purviance <jsgpurviance@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8dd7642
13 files changed+522 added−4 removed
added:docs/tutorial/parameter-types/custom_types.md+27 added
123456789101112131415161718192021222324252627You can easily use your own custom types in your **Typer** applications.
The way to do it is by providing a way to <abbr title="convert from some plain format, like the input text in the CLI, into Python objects">parse</abbr> input into your own types.
There are two ways to achieve this:
* Adding a type `parser`* Expanding Click's custom types
## Type Parser
`typer.Argument` and `typer.Option` can create custom parameter types with a `parser` <abbr title="something that can be called like a function">callable</abbr>.
```Python hl_lines="12-13 17 18"{!../docs_src/parameter_types/custom_types/tutorial001.py!}```
The function (or callable) that you pass to the parameter `parser` will receive the input value as a string and should return the parsed value with your own custom type.
## Click Custom Type
If you already have a <a href="https://click.palletsprojects.com/en/8.1.x/parameters/#implementing-custom-types" class="external-link" target="_blank">Click Custom Type</a>, you can use it in `typer.Argument()` and `typer.Option()` with the `click_type` parameter.
```Python hl_lines="13-17 21 22"{!../docs_src/parameter_types/custom_types/tutorial002.py!}```added:docs_src/parameter_types/custom_types/__init__.py
added:docs_src/parameter_types/custom_types/tutorial001.py+25 added
1+import typer2+3+4+class CustomClass:5+ def __init__(self, value: str):6+ self.value = value7+8+ def __str__(self):9+ return f"<CustomClass: value={self.value}>"10+11+12+def parse_custom_class(value: str):13+ return CustomClass(value * 2)14+15+16+def 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}")22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs_src/parameter_types/custom_types/tutorial002.py+29 added
1+import click2+import typer3+4+5+class CustomClass:6+ def __init__(self, value: str):7+ self.value = value8+9+ def __repr__(self):10+ return f"<CustomClass: value={self.value}>"11+12+13+class CustomClassParser(click.ParamType):14+ name = "CustomClass"15+16+ def convert(self, value, param, ctx):17+ return CustomClass(value * 3)18+19+20+def 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}")26+27+28+if __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
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.custom_types import tutorial001 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+19+20+def 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.output24+25+26+def 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.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial002.py+39 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.custom_types import tutorial002 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+19+20+def 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.output24+25+26+def 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.output30+31+32+def 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.stdoutmodified:tests/test_others.py+46 added-1 removed
1 import os2 import subprocess3 import sys4+import typing5 from pathlib import Path6 from unittest import mock7 8 import click1 unmodified line10 import shellingham11 import typer12 import typer.completion13 from typer.main import solve_typer_info_defaults, solve_typer_info_help13-from typer.models import TyperInfo14+from typer.models import ParameterInfo, TyperInfo15 from typer.testing import CliRunner16 17 runner = CliRunner()18 9 unmodified lines28 value = solve_typer_info_defaults(TyperInfo())29 assert value30 31 32+def test_too_may_parsers():33+ def custom_parser(value: str) -> int:34+ return int(value) # pragma: no cover35+36+ class CustomClickParser(click.ParamType):37+ name = "custom_parser"38+39+ 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 cover46+47+ expected_error = (48+ "Multiple custom type parsers provided. "49+ "`parser` and `click_type` may not both be provided."50+ )51+52+ with pytest.raises(ValueError, match=expected_error):53+ ParameterInfo(parser=custom_parser, click_type=CustomClickParser())54+55+56+def test_valid_parser_permutations():57+ def custom_parser(value: str) -> int:58+ return int(value) # pragma: no cover59+60+ class CustomClickParser(click.ParamType):61+ name = "custom_parser"62+63+ 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 cover70+71+ ParameterInfo()72+ ParameterInfo(parser=custom_parser)73+ ParameterInfo(click_type=CustomClickParser())74+75+76 def test_install_invalid_shell():77 app = typer.Typer()78 79 @app.command()178 unmodified linesmodified:tests/test_type_conversion.py+39 added-1 removed
1 from enum import Enum2 from pathlib import Path3-from typing import List, Optional, Tuple3+from typing import Any, List, Optional, Tuple4 5+import click6 import pytest7 import typer8 from typer.testing import CliRunner9 80 unmodified lines90 assert isinstance(element, expected_type)91 92 result = runner.invoke(app, ["one", "two"])93 assert result.exit_code == 094+95+96+def test_custom_parse():97+ app = typer.Typer()98+99+ @app.command()100+ def custom_parser(101+ hex_value: int = typer.Argument(None, parser=lambda x: int(x, 0))102+ ):103+ assert hex_value == 0x56104+105+ result = runner.invoke(app, ["0x56"])106+ assert result.exit_code == 0107+108+109+def test_custom_click_type():110+ class BaseNumberParamType(click.ParamType):111+ name = "base_integer"112+113+ def convert(114+ self,115+ value: Any,116+ param: Optional[click.Parameter],117+ ctx: Optional[click.Context],118+ ) -> Any:119+ return int(value, 0)120+121+ app = typer.Typer()122+123+ @app.command()124+ def custom_click_type(125+ hex_value: int = typer.Argument(None, click_type=BaseNumberParamType())126+ ):127+ assert hex_value == 0x56128+129+ result = runner.invoke(app, ["0x56"])130+ assert result.exit_code == 0modified:typer/main.py+7 added-1 removed
687 unmodified lines688 689 def 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_type694+695+ elif parameter_info.parser is not None:696+ return click.types.FuncParamType(parameter_info.parser)697+692- 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_ = None354 unmodified linesmodified:typer/models.py+25 added
182 unmodified lines183 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 lines218 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+ )228+229 self.default = default230 self.param_decls = param_decls231 self.callback = callback232 self.metavar = metavar1 unmodified line234 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_envvar44 unmodified lines289 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 lines342 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 lines406 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 lines451 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 linesmodified:typer/params.py+245 added-1 removed
1-from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union1+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, overload2 3 import click4 5 from .models import ArgumentInfo, OptionInfo1 unmodified line7 if TYPE_CHECKING: # pragma: no cover8 import click.shell_completion9 10 11+@overload12 def Option(13 # Parameter14 default: Optional[Any],15 *param_decls: str,8 unmodified lines24 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 lines66 path_type: Union[None, Type[str], Type[bytes]] = None,67 # Rich settings68 rich_help_panel: Union[str, None] = None,69 ) -> Any:70+ ...71+72+73+@overload74+def 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+ ...133+134+135+def 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 lines201 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 lines246 rich_help_panel=rich_help_panel,247 )248 249 250+@overload251 def Argument(252 # Parameter253 default: Optional[Any],254 *,8 unmodified lines263 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 lines297 path_type: Union[None, Type[str], Type[bytes]] = None,298 # Rich settings299 rich_help_panel: Union[str, None] = None,300 ) -> Any:301+ ...302+303+304+@overload305+def 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+ ...356+357+358+def 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 declaration5 unmodified lines418 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 linesmodified:mkdocs.yml+1 added
58 unmodified lines59 - 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.md66 unmodified lines