📝 Update docs examples for custom param types using `Annotated`, fix overloads for `typer.Argument` (#594)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* 📝 Add source examples for custom parameter types with Annotated * ✅ Add tests for custom parameters with Annotated * 📝 Update docs for custom parameters with Annotated * ♻️ Fix overloads default in Argument after Annotated * ✅ Fix test for custom param types
authored by Sebastián Ramírez · committed by GitHub · parent 8c59b68 · Browse files · 9 files·+169 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+169 added−12 removed
- tests:+79 added−1 removed
- other:+90 added−11 removed
Provenance
- Commit
58522bf- Tree
b2c2c5b- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8c59b68
9 files changed+169 added−12 removed
modified:docs/tutorial/parameter-types/custom-types.md+27 added-6 removed
9 unmodified lines1011121314151516171617181920212223242526272829303132333435363738394041424344452526274647489 unmodified lines## 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 3.6+"
```Python hl_lines="12-13 17 18"{!../docs_src/parameter_types/custom_types/tutorial001.py!}``` ```Python hl_lines="13-14 18-19" {!> ../docs_src/parameter_types/custom_types/tutorial001_an.py!} ```
=== "Python 3.6+ non-Annotated"
!!! tip Prefer to use the `Annotated` version if possible.
```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 3.6+"
```Python hl_lines="14-18 22-25" {!> ../docs_src/parameter_types/custom_types/tutorial002_an.py!} ```
=== "Python 3.6+ non-Annotated"
!!! tip Prefer to use the `Annotated` version if possible.
```Python hl_lines="13-17 21 22"{!../docs_src/parameter_types/custom_types/tutorial002.py!}``` ```Python hl_lines="13-17 21-22" {!> ../docs_src/parameter_types/custom_types/tutorial002.py!} ```added:docs_src/parameter_types/custom_types/tutorial001_an.py+26 added
1+import typer2+from typing_extensions import Annotated3+4+5+class CustomClass:6+ def __init__(self, value: str):7+ self.value = value8+9+ def __str__(self):10+ return f"<CustomClass: value={self.value}>"11+12+13+def parse_custom_class(value: str):14+ return CustomClass(value * 2)15+16+17+def main(18+ custom_arg: Annotated[CustomClass, typer.Argument(parser=parse_custom_class)],19+ custom_opt: Annotated[CustomClass, typer.Option(parser=parse_custom_class)] = "Foo",20+):21+ print(f"custom_arg is {custom_arg}")22+ print(f"--custom-opt is {custom_opt}")23+24+25+if __name__ == "__main__":26+ typer.run(main)modified:docs_src/parameter_types/custom_types/tutorial001.py+1 added-1 removed
12 unmodified lines13 return CustomClass(value * 2)14 15 16 def main(17- custom_arg: CustomClass = typer.Argument("X", parser=parse_custom_class),17+ custom_arg: CustomClass = typer.Argument(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}")4 unmodified linesadded:docs_src/parameter_types/custom_types/tutorial002_an.py+32 added
1+import click2+import typer3+from typing_extensions import Annotated4+5+6+class CustomClass:7+ def __init__(self, value: str):8+ self.value = value9+10+ def __repr__(self):11+ return f"<CustomClass: value={self.value}>"12+13+14+class CustomClassParser(click.ParamType):15+ name = "CustomClass"16+17+ def convert(self, value, param, ctx):18+ return CustomClass(value * 3)19+20+21+def main(22+ custom_arg: Annotated[CustomClass, typer.Argument(click_type=CustomClassParser())],23+ custom_opt: Annotated[24+ CustomClass, typer.Option(click_type=CustomClassParser())25+ ] = "Foo",26+):27+ print(f"custom_arg is {custom_arg}")28+ print(f"--custom-opt is {custom_opt}")29+30+31+if __name__ == "__main__":32+ typer.run(main)modified:docs_src/parameter_types/custom_types/tutorial002.py+2 added-2 removed
16 unmodified lines17 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()),21+ custom_arg: CustomClass = typer.Argument(click_type=CustomClassParser()),22+ custom_opt: CustomClass = typer.Option("Foo", click_type=CustomClassParser()),23 ):24 print(f"custom_arg is {custom_arg}")25 print(f"--custom-opt is {custom_opt}")26 3 unmodified linesadded:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial001_an.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_an 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=FooFoo>" 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_an.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_an 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=FooFooFoo>" 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_tutorial/test_parameter_types/test_custom_types/test_tutorial002.py+1 added-1 removed
24 unmodified lines25 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.output29+ assert "custom-opt is <CustomClass: value=FooFooFoo>" in result.output30 31 32 def test_script():33 result = subprocess.run(6 unmodified linesmodified:typer/params.py+2 added-2 removed
252 unmodified lines253 254 @overload255 def Argument(256 # Parameter257- default: Optional[Any],257+ default: Optional[Any] = ...,258 *,259 callback: Optional[Callable[..., Any]] = None,260 metavar: Optional[str] = None,261 expose_value: bool = True,45 unmodified lines307 308 @overload309 def Argument(310 # Parameter311- default: Optional[Any],311+ default: Optional[Any] = ...,312 *,313 callback: Optional[Callable[..., Any]] = None,314 metavar: Optional[str] = None,315 expose_value: bool = True,147 unmodified lines