🎨 Upgrade types for Python 3.10 (#1549)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent f2f911c · Browse files · 12 files·+358 added−383 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+358 added−383 removed
- tests:+8 added−13 removed
- other:+350 added−370 removed
Provenance
- Commit
829576c- Tree
c62b69b- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
f2f911c
12 files changed+358 added−383 removed
modified:scripts/mkdocs_hooks.py+4 added-4 removed
1-from typing import Any, Union1+from typing import Any2 3 from mkdocs.config.defaults import MkDocsConfig4 from mkdocs.structure.files import Files5 from mkdocs.structure.nav import Link, Navigation, Section6 from mkdocs.structure.pages import Page7 8 9 def generate_renamed_section_items(10- items: list[Union[Page, Section, Link]], *, config: MkDocsConfig11-) -> list[Union[Page, Section, Link]]:12- new_items: list[Union[Page, Section, Link]] = []10+ items: list[Page | Section | Link], *, config: MkDocsConfig11+) -> list[Page | Section | Link]:12+ new_items: list[Page | Section | Link] = []13 for item in items:14 if isinstance(item, Section):15 new_title = item.title16 new_children = generate_renamed_section_items(item.children, config=config)22 unmodified linesmodified:tests/test_completion/test_sanitization.py+1 added-2 removed
1 from importlib.machinery import ModuleSpec2-from typing import Union2 from unittest.mock import patch3 4 import pytest5 from typer._completion_classes import _sanitize_help_text24 unmodified lines30 ),31 ],32 )33 def test_sanitize_help_text(35- find_spec: Union[ModuleSpec, None], help_text: str, expected: str34+ find_spec: ModuleSpec | None, help_text: str, expected: str35 ):36 with patch("importlib.util.find_spec", return_value=find_spec) as mock_find_spec:37 assert _sanitize_help_text(help_text) == expected38 mock_find_spec.assert_called_once_with("rich")modified:tests/test_deprecation.py+1 added-3 removed
1-from typing import Optional2-1 import pytest2 import typer3 from typer.testing import CliRunner4 5 unmodified lines10 11 def add_command():12 @app.command()13 def cmd(16- opt: Optional[float] = typer.Option(14+ opt: float | None = typer.Option(15 3.14,16 is_flag=True,17 flag_value="42",18 help="Some wonderful number",7 unmodified linesmodified:tests/test_others.py+6 added-8 removed
41 unmodified lines42 43 def convert(44 self,45 value: str,46- param: typing.Optional[click.Parameter],47- ctx: typing.Optional[click.Context],46+ param: click.Parameter | None,47+ ctx: click.Context | None,48 ) -> typing.Any:49 return int(value) # pragma: no cover50 51 expected_error = (14 unmodified lines66 67 def convert(68 self,69 value: str,70- param: typing.Optional[click.Parameter],71- ctx: typing.Optional[click.Context],70+ param: click.Parameter | None,71+ ctx: click.Context | None,72 ) -> typing.Any:73 return int(value) # pragma: no cover74 75 ParameterInfo()71 unmodified lines147 148 def test_callback_4_list_none():149 app = typer.Typer()150 151- def names_callback(ctx, param, values: typing.Optional[list[str]]):151+ def names_callback(ctx, param, values: list[str] | None):152 if values is None:153 return values154 return [value.upper() for value in values]155 156 @app.command()157 def main(158- names: typing.Optional[list[str]] = typer.Option(159- None, "--name", callback=names_callback160- ),158+ names: list[str] | None = typer.Option(None, "--name", callback=names_callback),159 ):160 if names is None:161 print("Hello World")162 else:177 unmodified linesmodified:typer/_completion_classes.py+5 added-12 removed
5 unmodified lines6 7 import click8 import click.parser9 import click.shell_completion10+from click.shell_completion import split_arg_string as click_split_arg_string11 12 from ._completion_shared import (13 COMPLETION_SCRIPT_BASH,14 COMPLETION_SCRIPT_FISH,1 unmodified line16 COMPLETION_SCRIPT_ZSH,17 Shells,18 )19 19-try:20- from click.shell_completion import split_arg_string as click_split_arg_string21-except ImportError: # pragma: no cover22- # TODO: when removing support for Click < 8.2, remove this import23- from click.parser import ( # type: ignore[no-redef]24- split_arg_string as click_split_arg_string,25- )20 27-21 def _sanitize_help_text(text: str) -> str:22 """Sanitizes the help text by removing rich tags"""23 if not importlib.util.find_spec("rich"):24 return text13 unmodified lines38 "prog_name": self.prog_name,39 }40 41 def get_completion_args(self) -> tuple[list[str], str]:49- cwords = click_split_arg_string(os.environ["COMP_WORDS"]) # ty: ignore[call-non-callable]42+ cwords = click_split_arg_string(os.environ["COMP_WORDS"])43 cword = int(os.environ["COMP_CWORD"])44 args = cwords[1:cword]45 46 try:28 unmodified lines75 }76 77 def get_completion_args(self) -> tuple[list[str], str]:78 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")86- cwords = click_split_arg_string(completion_args) # ty: ignore[call-non-callable]79+ cwords = click_split_arg_string(completion_args)80 args = cwords[1:]81 if args and not completion_args.endswith(" "):82 incomplete = args[-1]83 args = args[:-1]42 unmodified lines126 }127 128 def get_completion_args(self) -> tuple[list[str], str]:129 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")137- cwords = click_split_arg_string(completion_args) # ty: ignore[call-non-callable]130+ cwords = click_split_arg_string(completion_args)131 args = cwords[1:]132 if args and not completion_args.endswith(" "):133 incomplete = args[-1]134 args = args[:-1]45 unmodified lines180 181 def get_completion_args(self) -> tuple[list[str], str]:182 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")183 incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")191- cwords = click_split_arg_string(completion_args) # ty: ignore[call-non-callable]184+ cwords = click_split_arg_string(completion_args)185 args = cwords[1:-1] if incomplete else cwords[1:]186 return args, incomplete187 188 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:11 unmodified linesmodified:typer/_completion_shared.py+5 added-6 removed
1 unmodified line2 import re3 import subprocess4 from enum import Enum5 from pathlib import Path6-from typing import Optional, Union6 7 import click8 import shellingham9 188 unmodified lines198 return path_obj199 200 201 def install(203- shell: Optional[str] = None,204- prog_name: Optional[str] = None,205- complete_var: Optional[str] = None,202+ shell: str | None = None,203+ prog_name: str | None = None,204+ complete_var: str | None = None,205 ) -> tuple[str, Path]:206 prog_name = prog_name or click.get_current_context().find_root().info_name207 assert prog_name208 if complete_var is None:25 unmodified lines234 click.echo(f"Shell {shell} is not supported.")235 raise click.exceptions.Exit(1)236 237 239-def _get_shell_name() -> Union[str, None]:238+def _get_shell_name() -> str | None:239 """Get the current shell name, if available.240 241 The name will always be lowercase. If the shell cannot be detected, None is242 returned.243 """245- name: Union[str, None] # N.B. shellingham is untyped244+ name: str | None # N.B. shellingham is untyped245 try:246 # N.B. detect_shell returns a tuple of (shell name, shell command).247 # We only need the name.248 name, _cmd = shellingham.detect_shell() # noqa: TID2514 unmodified linesmodified:typer/_types.py+3 added-3 removed
1 from enum import Enum2-from typing import Generic, TypeVar, Union2+from typing import TypeVar3 4 import click5 6 ParamTypeValue = TypeVar("ParamTypeValue")7 8 9-class TyperChoice(click.Choice, Generic[ParamTypeValue]): # type: ignore[type-arg]9+class TyperChoice(click.Choice[ParamTypeValue]):10 def normalize_choice(11- self, choice: ParamTypeValue, ctx: Union[click.Context, None]11+ self, choice: ParamTypeValue, ctx: click.Context | None12 ) -> str:13 # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class14 # to support enums, but it uses the enum names, while Typer has always used the15 # enum values.12 unmodified linesmodified:typer/cli.py+12 added-12 removed
1 import importlib.util2 import re3 import sys4 from pathlib import Path5-from typing import Any, Optional5+from typing import Any6 7 import click8 import typer9 import typer.core11 unmodified lines21 22 23 class State:24 def __init__(self) -> None:25- self.app: Optional[str] = None26- self.func: Optional[str] = None27- self.file: Optional[Path] = None28- self.module: Optional[str] = None25+ self.app: str | None = None26+ self.func: str | None = None27+ self.file: Path | None = None28+ self.module: str | None = None29 30 31 state = State()32 23 unmodified lines56 def list_commands(self, ctx: click.Context) -> list[str]:57 self.maybe_add_run(ctx)58 return super().list_commands(ctx)59 60- def get_command(self, ctx: click.Context, name: str) -> Optional[Command]: # ty: ignore[invalid-method-override]60+ def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]61 self.maybe_add_run(ctx)62 return super().get_command(ctx, name)63 64 def invoke(self, ctx: click.Context) -> Any:4 unmodified lines69 maybe_update_state(ctx)70 maybe_add_run_to_cli(self)71 72 73-def get_typer_from_module(module: Any) -> Optional[typer.Typer]:73+def get_typer_from_module(module: Any) -> typer.Typer | None:74 # Try to get defined app75 if state.app:76 obj = getattr(module, state.app, None)77 if not isinstance(obj, typer.Typer):39 unmodified lines117 return sub_app118 return None119 120 121-def get_typer_from_state() -> Optional[typer.Typer]:121+def get_typer_from_state() -> typer.Typer | None:122 spec = None123 if state.file:124 module_name = state.file.name125 spec = importlib.util.spec_from_file_location(module_name, str(state.file))4 unmodified lines130 typer.echo(f"Could not import as Python file: {state.file}", err=True)131 else:132 typer.echo(f"Could not import as Python module: {state.module}", err=True)133 sys.exit(1)134- module = importlib.util.module_from_spec(spec) # ty: ignore[invalid-argument-type]134+ module = importlib.util.module_from_spec(spec)135 spec.loader.exec_module(module) # type: ignore136 obj = get_typer_from_module(module)137 return obj138 50 unmodified lines189 ctx: typer.Context,190 indent: int = 0,191 name: str = "",192 call_prefix: str = "",193- title: Optional[str] = None,193+ title: str | None = None,194 ) -> str:195 docs = "#" * (1 + indent)196 command_name = name or obj.name197 if call_prefix:80 unmodified lines278 @utils_app.command()279 def docs(280 ctx: typer.Context,281 name: str = typer.Option("", help="The name of the CLI program to use in docs."),282- output: Optional[Path] = typer.Option(282+ output: Path | None = typer.Option(283 None,284 help="An output file to write docs to, like README.md.",285 file_okay=True,286 dir_okay=False,287 ),288- title: Optional[str] = typer.Option(288+ title: str | None = typer.Option(289 None,290 help="The title for the documentation page. If not provided, the name of "291 "the program is used.",292 ),25 unmodified linesmodified:typer/main.py+69 added-71 removed
3 unmodified lines4 import shutil5 import subprocess6 import sys7 import traceback8-from collections.abc import Sequence8+from collections.abc import Callable, Sequence9 from datetime import datetime10 from enum import Enum11 from functools import update_wrapper12 from pathlib import Path13 from traceback import FrameSummary, StackSummary14 from types import TracebackType15-from typing import Annotated, Any, Callable, Optional, Union15+from typing import Annotated, Any16 from uuid import UUID17 18 import click19 from annotated_doc import Doc36 unmodified lines56 _typer_developer_exception_attr_name = "__typer_developer_exception__"57 58 59 def except_hook(60- exc_type: type[BaseException], exc_value: BaseException, tb: Optional[TracebackType]60+ exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None61 ) -> None:62- exception_config: Union[DeveloperExceptionConfig, None] = getattr(62+ exception_config: DeveloperExceptionConfig | None = getattr(63 exc_value, _typer_developer_exception_attr_name, None64 )65 standard_traceback = os.getenv(66 "TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK")5 unmodified lines72 ):73 _original_except_hook(exc_type, exc_value, tb)74 return75 typer_path = os.path.dirname(__file__)76- click_path = os.path.dirname(click.__file__) # ty: ignore[no-matching-overload]76+ click_path = os.path.dirname(click.__file__)77 internal_dir_names = [typer_path, click_path]78 exc = exc_value79 if HAS_RICH:80 from . import rich_utils52 unmodified lines133 def __init__(134 self,135 *,136 name: Annotated[137- Optional[str],137+ str | None,138 Doc(139 """140 The name of this application.141 Mostly used to set the name for [subcommands](https://typer.tiangolo.com/tutorial/subcommands/), in which case it can be overridden by `add_typer(name=...)`.8 unmodified lines150 """151 ),152 ] = Default(None),153 cls: Annotated[154- Optional[type[TyperGroup]],154+ type[TyperGroup] | None,155 Doc(156 """157 The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.158 Otherwise, should be a subtype of `TyperGroup`.40 unmodified lines199 """200 ),201 ] = Default(False),202 subcommand_metavar: Annotated[203- Optional[str],203+ str | None,204 Doc(205 """206 **Note**: you probably shouldn't use this parameter, it is inherited207 from Click and supported for compatibility.17 unmodified lines225 """226 ),227 ] = Default(False),228 result_callback: Annotated[229- Optional[Callable[..., Any]],229+ Callable[..., Any] | None,230 Doc(231 """232 **Note**: you probably shouldn't use this parameter, it is inherited233 from Click and supported for compatibility.5 unmodified lines239 ),240 ] = Default(None),241 # Command242 context_settings: Annotated[243- Optional[dict[Any, Any]],243+ dict[Any, Any] | None,244 Doc(245 """246 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).247 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).8 unmodified lines256 """257 ),258 ] = Default(None),259 callback: Annotated[260- Optional[Callable[..., Any]],260+ Callable[..., Any] | None,261 Doc(262 """263 Add a callback to the main Typer app. Can be overridden with `@app.callback()`.264 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.11 unmodified lines276 """277 ),278 ] = Default(None),279 help: Annotated[280- Optional[str],280+ str | None,281 Doc(282 """283 Help text for the main Typer app.284 See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,9 unmodified lines294 """295 ),296 ] = Default(None),297 epilog: Annotated[298- Optional[str],298+ str | None,299 Doc(300 """301 Text that will be printed right after the help text.302 7 unmodified lines310 """311 ),312 ] = Default(None),313 short_help: Annotated[314- Optional[str],314+ str | None,315 Doc(316 """317 A shortened version of the help text that can be used e.g. in the help table listing subcommands.318 When not defined, the normal `help` text will be used instead.106 unmodified lines425 """426 ),427 ] = DEFAULT_MARKUP_MODE,428 rich_help_panel: Annotated[429- Union[str, None],429+ str | None,430 Doc(431 """432 Set the panel name of the command when the help is printed with Rich.433 107 unmodified lines541 deprecated=deprecated,542 )543 self.registered_groups: list[TyperInfo] = []544 self.registered_commands: list[CommandInfo] = []545- self.registered_callback: Optional[TyperInfo] = None545+ self.registered_callback: TyperInfo | None = None546 547 def callback(548 self,549 *,550 cls: Annotated[551- Optional[type[TyperGroup]],551+ type[TyperGroup] | None,552 Doc(553 """554 The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.555 Otherwise, should be a subtype of `TyperGroup`.16 unmodified lines572 """573 ),574 ] = Default(False),575 subcommand_metavar: Annotated[576- Optional[str],576+ str | None,577 Doc(578 """579 **Note**: you probably shouldn't use this parameter, it is inherited580 from Click and supported for compatibility.17 unmodified lines598 """599 ),600 ] = Default(False),601 result_callback: Annotated[602- Optional[Callable[..., Any]],602+ Callable[..., Any] | None,603 Doc(604 """605 **Note**: you probably shouldn't use this parameter, it is inherited606 from Click and supported for compatibility.5 unmodified lines612 ),613 ] = Default(None),614 # Command615 context_settings: Annotated[616- Optional[dict[Any, Any]],616+ dict[Any, Any] | None,617 Doc(618 """619 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).620 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).621 """622 ),623 ] = Default(None),624 help: Annotated[625- Optional[str],625+ str | None,626 Doc(627 """628 Help text for the command.629 See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,1 unmodified line631 """632 ),633 ] = Default(None),634 epilog: Annotated[635- Optional[str],635+ str | None,636 Doc(637 """638 Text that will be printed right after the help text.639 """640 ),641 ] = Default(None),642 short_help: Annotated[643- Optional[str],643+ str | None,644 Doc(645 """646 A shortened version of the help text that can be used e.g. in the help table listing subcommands.647 When not defined, the normal `help` text will be used instead.648 """649 ),650 ] = Default(None),651 options_metavar: Annotated[652- Optional[str],652+ str | None,653 Doc(654 """655 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.656 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.30 unmodified lines687 ),688 ] = Default(False),689 # Rich settings690 rich_help_panel: Annotated[691- Union[str, None],691+ str | None,692 Doc(693 """694 Set the panel name of the command when the help is printed with Rich.695 """54 unmodified lines750 751 def command(752 self,753 name: Annotated[754- Optional[str],754+ str | None,755 Doc(756 """757 The name of this command.758 """759 ),760 ] = None,761 *,762 cls: Annotated[763- Optional[type[TyperCommand]],763+ type[TyperCommand] | None,764 Doc(765 """766 The class of this command. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.767 Otherwise, should be a subtype of `TyperCommand`.768 """769 ),770 ] = None,771 context_settings: Annotated[772- Optional[dict[Any, Any]],772+ dict[Any, Any] | None,773 Doc(774 """775 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).776 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).777 """778 ),779 ] = None,780 help: Annotated[781- Optional[str],781+ str | None,782 Doc(783 """784 Help text for the command.785 See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,1 unmodified line787 """788 ),789 ] = None,790 epilog: Annotated[791- Optional[str],791+ str | None,792 Doc(793 """794 Text that will be printed right after the help text.795 """796 ),797 ] = None,798 short_help: Annotated[799- Optional[str],799+ str | None,800 Doc(801 """802 A shortened version of the help text that can be used e.g. in the help table listing subcommands.803 When not defined, the normal `help` text will be used instead.804 """805 ),806 ] = None,807 options_metavar: Annotated[808- Optional[str],808+ str | None,809 Doc(810 """811 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.812 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.38 unmodified lines851 ),852 ] = False,853 # Rich settings854 rich_help_panel: Annotated[855- Union[str, None],855+ str | None,856 Doc(857 """858 Set the panel name of the command when the help is printed with Rich.859 """54 unmodified lines914 self,915 typer_instance: "Typer",916 *,917 name: Annotated[918- Optional[str],918+ str | None,919 Doc(920 """921 The name of this subcommand.922 See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's name,1 unmodified line924 """925 ),926 ] = Default(None),927 cls: Annotated[928- Optional[type[TyperGroup]],928+ type[TyperGroup] | None,929 Doc(930 """931 The class of this subcommand. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.932 Otherwise, should be a subtype of `TyperGroup`.16 unmodified lines949 """950 ),951 ] = Default(False),952 subcommand_metavar: Annotated[953- Optional[str],953+ str | None,954 Doc(955 """956 **Note**: you probably shouldn't use this parameter, it is inherited957 from Click and supported for compatibility.17 unmodified lines975 """976 ),977 ] = Default(False),978 result_callback: Annotated[979- Optional[Callable[..., Any]],979+ Callable[..., Any] | None,980 Doc(981 """982 **Note**: you probably shouldn't use this parameter, it is inherited983 from Click and supported for compatibility.5 unmodified lines989 ),990 ] = Default(None),991 # Command992 context_settings: Annotated[993- Optional[dict[Any, Any]],993+ dict[Any, Any] | None,994 Doc(995 """996 Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).997 Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).998 """999 ),1000 ] = Default(None),1001 callback: Annotated[1002- Optional[Callable[..., Any]],1002+ Callable[..., Any] | None,1003 Doc(1004 """1005 Add a callback to this app.1006 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.1007 """1008 ),1009 ] = Default(None),1010 help: Annotated[1011- Optional[str],1011+ str | None,1012 Doc(1013 """1014 Help text for the subcommand.1015 See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,1 unmodified line1017 """1018 ),1019 ] = Default(None),1020 epilog: Annotated[1021- Optional[str],1021+ str | None,1022 Doc(1023 """1024 Text that will be printed right after the help text.1025 """1026 ),1027 ] = Default(None),1028 short_help: Annotated[1029- Optional[str],1029+ str | None,1030 Doc(1031 """1032 A shortened version of the help text that can be used e.g. in the help table listing subcommands.1033 When not defined, the normal `help` text will be used instead.1034 """1035 ),1036 ] = Default(None),1037 options_metavar: Annotated[1038- Optional[str],1038+ str | None,1039 Doc(1040 """1041 In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.1042 Set `options_metavar` to change this into a different string. When `None`, the default value will be used.30 unmodified lines1073 ),1074 ] = False,1075 # Rich settings1076 rich_help_panel: Annotated[1077- Union[str, None],1077+ str | None,1078 Doc(1079 """1080 Set the panel name of the command when the help is printed with Rich.1081 """278 unmodified lines1360 return name.lower().replace("_", "-")1361 1362 1363 def get_params_convertors_ctx_param_name_from_function(1364- callback: Optional[Callable[..., Any]],1365-) -> tuple[list[Union[click.Argument, click.Option]], dict[str, Any], Optional[str]]:1364+ callback: Callable[..., Any] | None,1365+) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]:1366 params = []1367 convertors = {}1368 context_param_name = None1369 if callback:15 unmodified lines1385 pretty_exceptions_short: bool,1386 rich_markup_mode: MarkupMode,1387 ) -> click.Command:1388 assert command_info.callback, "A command must have a callback function"1389- name = command_info.name or get_command_name(command_info.callback.__name__) # ty: ignore[possibly-missing-attribute]1389+ name = command_info.name or get_command_name(command_info.callback.__name__) # ty:ignore[unresolved-attribute]1390 use_help = command_info.help1391 if use_help is None:1392 use_help = inspect.getdoc(command_info.callback)1393 else:29 unmodified lines1423 )1424 return command1425 1426 1427-def determine_type_convertor(type_: Any) -> Optional[Callable[[Any], Any]]:1428- convertor: Optional[Callable[[Any], Any]] = None1427+def determine_type_convertor(type_: Any) -> Callable[[Any], Any] | None:1428+ convertor: Callable[[Any], Any] | None = None1429 if lenient_issubclass(type_, Path):1430 convertor = param_path_convertor1431 if lenient_issubclass(type_, Enum):1432 convertor = generate_enum_convertor(type_)1433 return convertor1434 1435 1436-def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:1436+def param_path_convertor(value: str | None = None) -> Path | None:1437 if value is not None:1438 # allow returning any subclass of Path created by an annotated parser without converting1439 # it back to a Path1440 return value if isinstance(value, Path) else Path(value)13 unmodified lines1454 return convertor1455 1456 1457 def generate_list_convertor(1458- convertor: Optional[Callable[[Any], Any]], default_value: Optional[Any]1459-) -> Callable[[Optional[Sequence[Any]]], Optional[list[Any]]]:1460- def internal_convertor(value: Optional[Sequence[Any]]) -> Optional[list[Any]]:1458+ convertor: Callable[[Any], Any] | None, default_value: Any | None1459+) -> Callable[[Sequence[Any] | None], list[Any] | None]:1460+ def internal_convertor(value: Sequence[Any] | None) -> list[Any] | None:1461 if (value is None) or (default_value is None and len(value) == 0):1462 return None1463 return [convertor(v) if convertor else v for v in value]1464 1 unmodified line1466 1467 1468 def generate_tuple_convertor(1469 types: Sequence[Any],1470-) -> Callable[[Optional[tuple[Any, ...]]], Optional[tuple[Any, ...]]]:1470+) -> Callable[[tuple[Any, ...] | None], tuple[Any, ...] | None]:1471 convertors = [determine_type_convertor(type_) for type_ in types]1472 1473 def internal_convertor(1474- param_args: Optional[tuple[Any, ...]],1475- ) -> Optional[tuple[Any, ...]]:1474+ param_args: tuple[Any, ...] | None,1475+ ) -> tuple[Any, ...] | None:1476 if param_args is None:1477 return None1478 return tuple(1479 convertor(arg) if convertor else arg1480- for (convertor, arg) in zip(convertors, param_args)1480+ for (convertor, arg) in zip(convertors, param_args, strict=False)1481 )1482 1483 return internal_convertor1484 1485 1486 def get_callback(1487 *,1488- callback: Optional[Callable[..., Any]] = None,1488+ callback: Callable[..., Any] | None = None,1489 params: Sequence[click.Parameter] = [],1490- convertors: Optional[dict[str, Callable[[str], Any]]] = None,1491- context_param_name: Optional[str] = None,1490+ convertors: dict[str, Callable[[str], Any]] | None = None,1491+ context_param_name: str | None = None,1492 pretty_exceptions_short: bool,1493-) -> Optional[Callable[..., Any]]:1493+) -> Callable[..., Any] | None:1494 use_convertors = convertors or {}1495 if not callback:1496 return None1497 parameters = get_params_from_function(callback)121 unmodified lines1619 )1620 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover1621 1622 1623-def lenient_issubclass(1624- cls: Any, class_or_tuple: Union[AnyType, tuple[AnyType, ...]]1625-) -> bool:1623+def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool:1624 return isinstance(cls, type) and issubclass(cls, class_or_tuple)1625 1626 1627 def get_click_param(1628 param: ParamMeta,1631-) -> tuple[Union[click.Argument, click.Option], Any]:1629+) -> tuple[click.Argument | click.Option, Any]:1630 # First, find out what will be:1631 # * ParamInfo (ArgumentInfo or OptionInfo)1632 # * default_value1633 # * required154 unmodified lines1788 1789 1790 def get_param_callback(1791 *,1794- callback: Optional[Callable[..., Any]] = None,1795- convertor: Optional[Callable[..., Any]] = None,1796-) -> Optional[Callable[..., Any]]:1792+ callback: Callable[..., Any] | None = None,1793+ convertor: Callable[..., Any] | None = None,1794+) -> Callable[..., Any] | None:1795 if not callback:1796 return None1797 parameters = get_params_from_function(callback)1798 ctx_name = None40 unmodified lines1839 return wrapper1840 1841 1842 def get_param_completion(1845- callback: Optional[Callable[..., Any]] = None,1846-) -> Optional[Callable[..., Any]]:1843+ callback: Callable[..., Any] | None = None,1844+) -> Callable[..., Any] | None:1845 if not callback:1846 return None1847 parameters = get_params_from_function(callback)1848 ctx_name = None28 unmodified lines1877 raise click.ClickException(1878 f"Invalid autocompletion callback parameters: {show_params}"1879 )1880 1883- def wrapper(ctx: click.Context, args: list[str], incomplete: Optional[str]) -> Any:1881+ def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any:1882 use_params: dict[str, Any] = {}1883 if ctx_name:1884 use_params[ctx_name] = ctx1885 if args_name:128 unmodified linesmodified:typer/models.py+97 added-102 removed
1 import inspect2 import io3-from collections.abc import Sequence3+from collections.abc import Callable, Sequence4 from typing import (5 TYPE_CHECKING,6 Any,7- Callable,7 Optional,8 TypeVar,10- Union,9 )10 11 import click12 import click.shell_completion181 unmodified lines194 195 class CommandInfo:196 def __init__(197 self,200- name: Optional[str] = None,198+ name: str | None = None,199 *,202- cls: Optional[type["TyperCommand"]] = None,203- context_settings: Optional[dict[Any, Any]] = None,204- callback: Optional[Callable[..., Any]] = None,205- help: Optional[str] = None,206- epilog: Optional[str] = None,207- short_help: Optional[str] = None,200+ cls: type["TyperCommand"] | None = None,201+ context_settings: dict[Any, Any] | None = None,202+ callback: Callable[..., Any] | None = None,203+ help: str | None = None,204+ epilog: str | None = None,205+ short_help: str | None = None,206 options_metavar: str = "[OPTIONS]",207 add_help_option: bool = True,208 no_args_is_help: bool = False,209 hidden: bool = False,210 deprecated: bool = False,211 # Rich settings214- rich_help_panel: Union[str, None] = None,212+ rich_help_panel: str | None = None,213 ):214 self.name = name215 self.cls = cls216 self.context_settings = context_settings14 unmodified lines231 def __init__(232 self,233 typer_instance: Optional["Typer"] = Default(None),234 *,237- name: Optional[str] = Default(None),238- cls: Optional[type["TyperGroup"]] = Default(None),235+ name: str | None = Default(None),236+ cls: type["TyperGroup"] | None = Default(None),237 invoke_without_command: bool = Default(False),238 no_args_is_help: bool = Default(False),241- subcommand_metavar: Optional[str] = Default(None),239+ subcommand_metavar: str | None = Default(None),240 chain: bool = Default(False),243- result_callback: Optional[Callable[..., Any]] = Default(None),241+ result_callback: Callable[..., Any] | None = Default(None),242 # Command245- context_settings: Optional[dict[Any, Any]] = Default(None),246- callback: Optional[Callable[..., Any]] = Default(None),247- help: Optional[str] = Default(None),248- epilog: Optional[str] = Default(None),249- short_help: Optional[str] = Default(None),243+ context_settings: dict[Any, Any] | None = Default(None),244+ callback: Callable[..., Any] | None = Default(None),245+ help: str | None = Default(None),246+ epilog: str | None = Default(None),247+ short_help: str | None = Default(None),248 options_metavar: str = Default("[OPTIONS]"),249 add_help_option: bool = Default(True),250 hidden: bool = Default(False),251 deprecated: bool = Default(False),252 # Rich settings255- rich_help_panel: Union[str, None] = Default(None),253+ rich_help_panel: str | None = Default(None),254 ):255 self.typer_instance = typer_instance256 self.name = name257 self.cls = cls17 unmodified lines275 class ParameterInfo:276 def __init__(277 self,278 *,281- default: Optional[Any] = None,282- param_decls: Optional[Sequence[str]] = None,283- callback: Optional[Callable[..., Any]] = None,284- metavar: Optional[str] = None,279+ default: Any | None = None,280+ param_decls: Sequence[str] | None = None,281+ callback: Callable[..., Any] | None = None,282+ metavar: str | None = None,283 expose_value: bool = True,284 is_eager: bool = False,287- envvar: Optional[Union[str, list[str]]] = None,285+ envvar: str | list[str] | None = None,286 # Note that shell_complete is not fully supported and will be removed in future versions287 # TODO: Remove shell_complete in a future version (after 0.16.0)290- shell_complete: Optional[291- Callable[292- [click.Context, click.Parameter, str],293- Union[list["click.shell_completion.CompletionItem"], list[str]],294- ]295- ] = None,296- autocompletion: Optional[Callable[..., Any]] = None,297- default_factory: Optional[Callable[[], Any]] = None,288+ shell_complete: Callable[289+ [click.Context, click.Parameter, str],290+ list["click.shell_completion.CompletionItem"] | list[str],291+ ]292+ | None = None,293+ autocompletion: Callable[..., Any] | None = None,294+ default_factory: Callable[[], Any] | None = None,295 # Custom type299- parser: Optional[Callable[[str], Any]] = None,300- click_type: Optional[click.ParamType] = None,296+ parser: Callable[[str], Any] | None = None,297+ click_type: click.ParamType | None = None,298 # TyperArgument302- show_default: Union[bool, str] = True,299+ show_default: bool | str = True,300 show_choices: bool = True,301 show_envvar: bool = True,305- help: Optional[str] = None,302+ help: str | None = None,303 hidden: bool = False,304 # Choice305 case_sensitive: bool = True,306 # Numbers310- min: Optional[Union[int, float]] = None,311- max: Optional[Union[int, float]] = None,307+ min: int | float | None = None,308+ max: int | float | None = None,309 clamp: bool = False,310 # DateTime314- formats: Optional[list[str]] = None,311+ formats: list[str] | None = None,312 # File316- mode: Optional[str] = None,317- encoding: Optional[str] = None,318- errors: Optional[str] = "strict",319- lazy: Optional[bool] = None,313+ mode: str | None = None,314+ encoding: str | None = None,315+ errors: str | None = "strict",316+ lazy: bool | None = None,317 atomic: bool = False,318 # Path319 exists: bool = False,320 file_okay: bool = True,1 unmodified line322 writable: bool = False,323 readable: bool = True,324 resolve_path: bool = False,325 allow_dash: bool = False,329- path_type: Union[None, type[str], type[bytes]] = None,326+ path_type: None | type[str] | type[bytes] = None,327 # Rich settings331- rich_help_panel: Union[str, None] = None,328+ rich_help_panel: str | None = None,329 ):330 # Check if user has provided multiple custom parsers331 if parser and click_type:332 raise ValueError(51 unmodified lines384 def __init__(385 self,386 *,387 # ParameterInfo391- default: Optional[Any] = None,392- param_decls: Optional[Sequence[str]] = None,393- callback: Optional[Callable[..., Any]] = None,394- metavar: Optional[str] = None,388+ default: Any | None = None,389+ param_decls: Sequence[str] | None = None,390+ callback: Callable[..., Any] | None = None,391+ metavar: str | None = None,392 expose_value: bool = True,393 is_eager: bool = False,397- envvar: Optional[Union[str, list[str]]] = None,394+ envvar: str | list[str] | None = None,395 # Note that shell_complete is not fully supported and will be removed in future versions396 # TODO: Remove shell_complete in a future version (after 0.16.0)400- shell_complete: Optional[401- Callable[402- [click.Context, click.Parameter, str],403- Union[list["click.shell_completion.CompletionItem"], list[str]],404- ]405- ] = None,406- autocompletion: Optional[Callable[..., Any]] = None,407- default_factory: Optional[Callable[[], Any]] = None,397+ shell_complete: Callable[398+ [click.Context, click.Parameter, str],399+ list["click.shell_completion.CompletionItem"] | list[str],400+ ]401+ | None = None,402+ autocompletion: Callable[..., Any] | None = None,403+ default_factory: Callable[[], Any] | None = None,404 # Custom type409- parser: Optional[Callable[[str], Any]] = None,410- click_type: Optional[click.ParamType] = None,405+ parser: Callable[[str], Any] | None = None,406+ click_type: click.ParamType | None = None,407 # Option412- show_default: Union[bool, str] = True,413- prompt: Union[bool, str] = False,408+ show_default: bool | str = True,409+ prompt: bool | str = False,410 confirmation_prompt: bool = False,411 prompt_required: bool = True,412 hide_input: bool = False,413 # TODO: remove is_flag and flag_value in a future release418- is_flag: Optional[bool] = None,419- flag_value: Optional[Any] = None,414+ is_flag: bool | None = None,415+ flag_value: Any | None = None,416 count: bool = False,417 allow_from_autoenv: bool = True,422- help: Optional[str] = None,418+ help: str | None = None,419 hidden: bool = False,420 show_choices: bool = True,421 show_envvar: bool = True,422 # Choice423 case_sensitive: bool = True,424 # Numbers429- min: Optional[Union[int, float]] = None,430- max: Optional[Union[int, float]] = None,425+ min: int | float | None = None,426+ max: int | float | None = None,427 clamp: bool = False,428 # DateTime433- formats: Optional[list[str]] = None,429+ formats: list[str] | None = None,430 # File435- mode: Optional[str] = None,436- encoding: Optional[str] = None,437- errors: Optional[str] = "strict",438- lazy: Optional[bool] = None,431+ mode: str | None = None,432+ encoding: str | None = None,433+ errors: str | None = "strict",434+ lazy: bool | None = None,435 atomic: bool = False,436 # Path437 exists: bool = False,438 file_okay: bool = True,1 unmodified line440 writable: bool = False,441 readable: bool = True,442 resolve_path: bool = False,443 allow_dash: bool = False,448- path_type: Union[None, type[str], type[bytes]] = None,444+ path_type: None | type[str] | type[bytes] = None,445 # Rich settings450- rich_help_panel: Union[str, None] = None,446+ rich_help_panel: str | None = None,447 ):448 super().__init__(449 default=default,450 param_decls=param_decls,61 unmodified lines512 def __init__(513 self,514 *,515 # ParameterInfo520- default: Optional[Any] = None,521- param_decls: Optional[Sequence[str]] = None,522- callback: Optional[Callable[..., Any]] = None,523- metavar: Optional[str] = None,516+ default: Any | None = None,517+ param_decls: Sequence[str] | None = None,518+ callback: Callable[..., Any] | None = None,519+ metavar: str | None = None,520 expose_value: bool = True,521 is_eager: bool = False,526- envvar: Optional[Union[str, list[str]]] = None,522+ envvar: str | list[str] | None = None,523 # Note that shell_complete is not fully supported and will be removed in future versions524 # TODO: Remove shell_complete in a future version (after 0.16.0)529- shell_complete: Optional[530- Callable[531- [click.Context, click.Parameter, str],532- Union[list["click.shell_completion.CompletionItem"], list[str]],533- ]534- ] = None,535- autocompletion: Optional[Callable[..., Any]] = None,536- default_factory: Optional[Callable[[], Any]] = None,525+ shell_complete: Callable[526+ [click.Context, click.Parameter, str],527+ list["click.shell_completion.CompletionItem"] | list[str],528+ ]529+ | None = None,530+ autocompletion: Callable[..., Any] | None = None,531+ default_factory: Callable[[], Any] | None = None,532 # Custom type538- parser: Optional[Callable[[str], Any]] = None,539- click_type: Optional[click.ParamType] = None,533+ parser: Callable[[str], Any] | None = None,534+ click_type: click.ParamType | None = None,535 # TyperArgument541- show_default: Union[bool, str] = True,536+ show_default: bool | str = True,537 show_choices: bool = True,538 show_envvar: bool = True,544- help: Optional[str] = None,539+ help: str | None = None,540 hidden: bool = False,541 # Choice542 case_sensitive: bool = True,543 # Numbers549- min: Optional[Union[int, float]] = None,550- max: Optional[Union[int, float]] = None,544+ min: int | float | None = None,545+ max: int | float | None = None,546 clamp: bool = False,547 # DateTime553- formats: Optional[list[str]] = None,548+ formats: list[str] | None = None,549 # File555- mode: Optional[str] = None,556- encoding: Optional[str] = None,557- errors: Optional[str] = "strict",558- lazy: Optional[bool] = None,550+ mode: str | None = None,551+ encoding: str | None = None,552+ errors: str | None = "strict",553+ lazy: bool | None = None,554 atomic: bool = False,555 # Path556 exists: bool = False,557 file_okay: bool = True,1 unmodified line559 writable: bool = False,560 readable: bool = True,561 resolve_path: bool = False,562 allow_dash: bool = False,568- path_type: Union[None, type[str], type[bytes]] = None,563+ path_type: None | type[str] | type[bytes] = None,564 # Rich settings570- rich_help_panel: Union[str, None] = None,565+ rich_help_panel: str | None = None,566 ):567 super().__init__(568 default=default,569 param_decls=param_decls,82 unmodified linesmodified:typer/params.py+151 added-156 removed
1+from collections.abc import Callable1-from typing import TYPE_CHECKING, Annotated, Any, Callable, Optional, Union, overload2+from typing import TYPE_CHECKING, Annotated, Any, overload3 4 import click5 from annotated_doc import Doc6 6 unmodified lines13 # Overload for Option created with custom type 'parser'14 @overload15 def Option(16 # Parameter16- default: Optional[Any] = ...,17+ default: Any | None = ...,18 *param_decls: str,18- callback: Optional[Callable[..., Any]] = None,19- metavar: Optional[str] = None,19+ callback: Callable[..., Any] | None = None,20+ metavar: str | None = None,21 expose_value: bool = True,22 is_eager: bool = False,22- envvar: Optional[Union[str, list[str]]] = None,23+ envvar: str | list[str] | None = None,24 # Note that shell_complete is not fully supported and will be removed in future versions25 # TODO: Remove shell_complete in a future version (after 0.16.0)25- shell_complete: Optional[26- Callable[27- [click.Context, click.Parameter, str],28- Union[list["click.shell_completion.CompletionItem"], list[str]],29- ]30- ] = None,31- autocompletion: Optional[Callable[..., Any]] = None,32- default_factory: Optional[Callable[[], Any]] = None,26+ shell_complete: Callable[27+ [click.Context, click.Parameter, str],28+ list["click.shell_completion.CompletionItem"] | list[str],29+ ]30+ | None = None,31+ autocompletion: Callable[..., Any] | None = None,32+ default_factory: Callable[[], Any] | None = None,33 # Custom type34- parser: Optional[Callable[[str], Any]] = None,34+ parser: Callable[[str], Any] | None = None,35 # Option36- show_default: Union[bool, str] = True,37- prompt: Union[bool, str] = False,36+ show_default: bool | str = True,37+ prompt: bool | str = False,38 confirmation_prompt: bool = False,39 prompt_required: bool = True,40 hide_input: bool = False,41 # TODO: remove is_flag and flag_value in a future release42- is_flag: Optional[bool] = None,43- flag_value: Optional[Any] = None,42+ is_flag: bool | None = None,43+ flag_value: Any | None = None,44 count: bool = False,45 allow_from_autoenv: bool = True,46- help: Optional[str] = None,46+ help: str | None = None,47 hidden: bool = False,48 show_choices: bool = True,49 show_envvar: bool = True,50 # Choice51 case_sensitive: bool = True,52 # Numbers53- min: Optional[Union[int, float]] = None,54- max: Optional[Union[int, float]] = None,53+ min: int | float | None = None,54+ max: int | float | None = None,55 clamp: bool = False,56 # DateTime57- formats: Optional[list[str]] = None,57+ formats: list[str] | None = None,58 # File59- mode: Optional[str] = None,60- encoding: Optional[str] = None,61- errors: Optional[str] = "strict",62- lazy: Optional[bool] = None,59+ mode: str | None = None,60+ encoding: str | None = None,61+ errors: str | None = "strict",62+ lazy: bool | None = None,63 atomic: bool = False,64 # Path65 exists: bool = False,66 file_okay: bool = True,1 unmodified line68 writable: bool = False,69 readable: bool = True,70 resolve_path: bool = False,71 allow_dash: bool = False,72- path_type: Union[None, type[str], type[bytes]] = None,72+ path_type: None | type[str] | type[bytes] = None,73 # Rich settings74- rich_help_panel: Union[str, None] = None,74+ rich_help_panel: str | None = None,75 ) -> Any: ...76 77 78 # Overload for Option created with custom type 'click_type'79 @overload80 def Option(81 # Parameter82- default: Optional[Any] = ...,82+ default: Any | None = ...,83 *param_decls: str,84- callback: Optional[Callable[..., Any]] = None,85- metavar: Optional[str] = None,84+ callback: Callable[..., Any] | None = None,85+ metavar: str | None = None,86 expose_value: bool = True,87 is_eager: bool = False,88- envvar: Optional[Union[str, list[str]]] = None,88+ envvar: str | list[str] | None = None,89 # Note that shell_complete is not fully supported and will be removed in future versions90 # TODO: Remove shell_complete in a future version (after 0.16.0)91- shell_complete: Optional[92- Callable[93- [click.Context, click.Parameter, str],94- Union[list["click.shell_completion.CompletionItem"], list[str]],95- ]96- ] = None,97- autocompletion: Optional[Callable[..., Any]] = None,98- default_factory: Optional[Callable[[], Any]] = None,91+ shell_complete: Callable[92+ [click.Context, click.Parameter, str],93+ list["click.shell_completion.CompletionItem"] | list[str],94+ ]95+ | None = None,96+ autocompletion: Callable[..., Any] | None = None,97+ default_factory: Callable[[], Any] | None = None,98 # Custom type100- click_type: Optional[click.ParamType] = None,99+ click_type: click.ParamType | None = None,100 # Option102- show_default: Union[bool, str] = True,103- prompt: Union[bool, str] = False,101+ show_default: bool | str = True,102+ prompt: bool | str = False,103 confirmation_prompt: bool = False,104 prompt_required: bool = True,105 hide_input: bool = False,106 # TODO: remove is_flag and flag_value in a future release108- is_flag: Optional[bool] = None,109- flag_value: Optional[Any] = None,107+ is_flag: bool | None = None,108+ flag_value: Any | None = None,109 count: bool = False,110 allow_from_autoenv: bool = True,112- help: Optional[str] = None,111+ help: str | None = None,112 hidden: bool = False,113 show_choices: bool = True,114 show_envvar: bool = True,115 # Choice116 case_sensitive: bool = True,117 # Numbers119- min: Optional[Union[int, float]] = None,120- max: Optional[Union[int, float]] = None,118+ min: int | float | None = None,119+ max: int | float | None = None,120 clamp: bool = False,121 # DateTime123- formats: Optional[list[str]] = None,122+ formats: list[str] | None = None,123 # File125- mode: Optional[str] = None,126- encoding: Optional[str] = None,127- errors: Optional[str] = "strict",128- lazy: Optional[bool] = None,124+ mode: str | None = None,125+ encoding: str | None = None,126+ errors: str | None = "strict",127+ lazy: bool | None = None,128 atomic: bool = False,129 # Path130 exists: bool = False,131 file_okay: bool = True,1 unmodified line133 writable: bool = False,134 readable: bool = True,135 resolve_path: bool = False,136 allow_dash: bool = False,138- path_type: Union[None, type[str], type[bytes]] = None,137+ path_type: None | type[str] | type[bytes] = None,138 # Rich settings140- rich_help_panel: Union[str, None] = None,139+ rich_help_panel: str | None = None,140 ) -> Any: ...141 142 143 def Option(144 # Parameter145 default: Annotated[147- Optional[Any],146+ Any | None,147 Doc(148 """149 Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this:150 34 unmodified lines185 """186 ),187 ],188 callback: Annotated[190- Optional[Callable[..., Any]],189+ Callable[..., Any] | None,190 Doc(191 """192 Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal.193 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.13 unmodified lines207 """208 ),209 ] = None,210 metavar: Annotated[212- Optional[str],211+ str | None,212 Doc(213 """214 Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option.215 Note that this doesn't influence the way the option must be called.29 unmodified lines245 """246 ),247 ] = False,248 envvar: Annotated[250- Optional[Union[str, list[str]]],249+ str | list[str] | None,250 Doc(251 """252 Configure a CLI Option to read its value from an environment variable if it is not provided in the command line.253 For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).9 unmodified lines263 ),264 ] = None,265 # TODO: Remove shell_complete in a future version (after 0.16.0)266 shell_complete: Annotated[268- Optional[269- Callable[270- [click.Context, click.Parameter, str],271- Union[list["click.shell_completion.CompletionItem"], list[str]],272- ]273- ],267+ Callable[268+ [click.Context, click.Parameter, str],269+ list["click.shell_completion.CompletionItem"] | list[str],270+ ]271+ | None,272 Doc(273 """274 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.275 It is however not fully functional, and will likely be removed in future versions.276 """277 ),278 ] = None,279 autocompletion: Annotated[282- Optional[Callable[..., Any]],280+ Callable[..., Any] | None,281 Doc(282 """283 Provide a custom function that helps to autocomplete the values of this CLI Option.284 See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.11 unmodified lines296 """297 ),298 ] = None,299 default_factory: Annotated[302- Optional[Callable[[], Any]],300+ Callable[[], Any] | None,301 Doc(302 """303 Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option.304 11 unmodified lines316 ),317 ] = None,318 # Custom type319 parser: Annotated[322- Optional[Callable[[str], Any]],320+ Callable[[str], Any] | None,321 Doc(322 """323 Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:324 17 unmodified lines342 """343 ),344 ] = None,345 click_type: Annotated[348- Optional[click.ParamType],346+ click.ParamType | None,347 Doc(348 """349 Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.350 21 unmodified lines372 ),373 ] = None,374 # Option375 show_default: Annotated[378- Union[bool, str],376+ bool | str,377 Doc(378 """379 When set to `False`, don't show the default value of this CLI Option in the [help text](https://typer.tiangolo.com/tutorial/options/help/).380 7 unmodified lines388 """389 ),390 ] = True,391 prompt: Annotated[394- Union[bool, str],392+ bool | str,393 Doc(394 """395 When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided:396 56 unmodified lines453 ),454 ] = False,455 # TODO: remove is_flag and flag_value in a future release456 is_flag: Annotated[459- Optional[bool],457+ bool | None,458 Doc(459 """460 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.461 It is however not fully functional, and will likely be removed in future versions.462 """463 ),464 ] = None,465 flag_value: Annotated[468- Optional[Any],466+ Any | None,467 Doc(468 """469 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.470 It is however not fully functional, and will likely be removed in future versions.29 unmodified lines500 """501 ),502 ] = True,503 help: Annotated[506- Optional[str],504+ str | None,505 Doc(506 """507 Help text for this CLI Option.508 See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails.81 unmodified lines590 ),591 ] = True,592 # Numbers593 min: Annotated[596- Optional[Union[int, float]],594+ int | float | None,595 Doc(596 """597 For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),598 you can define numeric validations with `min` and `max` values:13 unmodified lines612 """613 ),614 ] = None,615 max: Annotated[618- Optional[Union[int, float]],616+ int | float | None,617 Doc(618 """619 For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),620 you can define numeric validations with `min` and `max` values:36 unmodified lines657 ),658 ] = False,659 # DateTime660 formats: Annotated[663- Optional[list[str]],661+ list[str] | None,662 Doc(663 """664 For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),665 you can customize the formats that can be parsed automatically:18 unmodified lines684 ),685 ] = None,686 # File687 mode: Annotated[690- Optional[str],688+ str | None,689 Doc(690 """691 For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),692 you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).9 unmodified lines702 """703 ),704 ] = None,705 encoding: Annotated[708- Optional[str],706+ str | None,707 Doc(708 """709 Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).710 7 unmodified lines718 """719 ),720 ] = None,721 errors: Annotated[724- Optional[str],722+ str | None,723 Doc(724 """725 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.726 3 unmodified lines730 """731 ),732 ] = "strict",733 lazy: Annotated[736- Optional[bool],734+ bool | None,735 Doc(736 """737 For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),738 by default the file will not be created until you actually start writing to it.153 unmodified lines892 """893 ),894 ] = False,895 path_type: Annotated[898- Union[None, type[str], type[bytes]],896+ None | type[str] | type[bytes],897 Doc(898 """899 A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).900 The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.2 unmodified lines903 ),904 ] = None,905 # Rich settings906 rich_help_panel: Annotated[909- Union[str, None],907+ str | None,908 Doc(909 """910 Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).911 91 unmodified lines1003 # Overload for Argument created with custom type 'parser'1004 @overload1005 def Argument(1006 # Parameter1009- default: Optional[Any] = ...,1007+ default: Any | None = ...,1008 *,1011- callback: Optional[Callable[..., Any]] = None,1012- metavar: Optional[str] = None,1009+ callback: Callable[..., Any] | None = None,1010+ metavar: str | None = None,1011 expose_value: bool = True,1012 is_eager: bool = False,1015- envvar: Optional[Union[str, list[str]]] = None,1013+ envvar: str | list[str] | None = None,1014 # Note that shell_complete is not fully supported and will be removed in future versions1015 # TODO: Remove shell_complete in a future version (after 0.16.0)1018- shell_complete: Optional[1019- Callable[1020- [click.Context, click.Parameter, str],1021- Union[list["click.shell_completion.CompletionItem"], list[str]],1022- ]1023- ] = None,1024- autocompletion: Optional[Callable[..., Any]] = None,1025- default_factory: Optional[Callable[[], Any]] = None,1016+ shell_complete: Callable[1017+ [click.Context, click.Parameter, str],1018+ list["click.shell_completion.CompletionItem"] | list[str],1019+ ]1020+ | None = None,1021+ autocompletion: Callable[..., Any] | None = None,1022+ default_factory: Callable[[], Any] | None = None,1023 # Custom type1027- parser: Optional[Callable[[str], Any]] = None,1024+ parser: Callable[[str], Any] | None = None,1025 # TyperArgument1029- show_default: Union[bool, str] = True,1026+ show_default: bool | str = True,1027 show_choices: bool = True,1028 show_envvar: bool = True,1032- help: Optional[str] = None,1029+ help: str | None = None,1030 hidden: bool = False,1031 # Choice1032 case_sensitive: bool = True,1033 # Numbers1037- min: Optional[Union[int, float]] = None,1038- max: Optional[Union[int, float]] = None,1034+ min: int | float | None = None,1035+ max: int | float | None = None,1036 clamp: bool = False,1037 # DateTime1041- formats: Optional[list[str]] = None,1038+ formats: list[str] | None = None,1039 # File1043- mode: Optional[str] = None,1044- encoding: Optional[str] = None,1045- errors: Optional[str] = "strict",1046- lazy: Optional[bool] = None,1040+ mode: str | None = None,1041+ encoding: str | None = None,1042+ errors: str | None = "strict",1043+ lazy: bool | None = None,1044 atomic: bool = False,1045 # Path1046 exists: bool = False,1047 file_okay: bool = True,1 unmodified line1049 writable: bool = False,1050 readable: bool = True,1051 resolve_path: bool = False,1052 allow_dash: bool = False,1056- path_type: Union[None, type[str], type[bytes]] = None,1053+ path_type: None | type[str] | type[bytes] = None,1054 # Rich settings1058- rich_help_panel: Union[str, None] = None,1055+ rich_help_panel: str | None = None,1056 ) -> Any: ...1057 1058 1059 # Overload for Argument created with custom type 'click_type'1060 @overload1061 def Argument(1062 # Parameter1066- default: Optional[Any] = ...,1063+ default: Any | None = ...,1064 *,1068- callback: Optional[Callable[..., Any]] = None,1069- metavar: Optional[str] = None,1065+ callback: Callable[..., Any] | None = None,1066+ metavar: str | None = None,1067 expose_value: bool = True,1068 is_eager: bool = False,1072- envvar: Optional[Union[str, list[str]]] = None,1069+ envvar: str | list[str] | None = None,1070 # Note that shell_complete is not fully supported and will be removed in future versions1071 # TODO: Remove shell_complete in a future version (after 0.16.0)1075- shell_complete: Optional[1076- Callable[1077- [click.Context, click.Parameter, str],1078- Union[list["click.shell_completion.CompletionItem"], list[str]],1079- ]1080- ] = None,1081- autocompletion: Optional[Callable[..., Any]] = None,1082- default_factory: Optional[Callable[[], Any]] = None,1072+ shell_complete: Callable[1073+ [click.Context, click.Parameter, str],1074+ list["click.shell_completion.CompletionItem"] | list[str],1075+ ]1076+ | None = None,1077+ autocompletion: Callable[..., Any] | None = None,1078+ default_factory: Callable[[], Any] | None = None,1079 # Custom type1084- click_type: Optional[click.ParamType] = None,1080+ click_type: click.ParamType | None = None,1081 # TyperArgument1086- show_default: Union[bool, str] = True,1082+ show_default: bool | str = True,1083 show_choices: bool = True,1084 show_envvar: bool = True,1089- help: Optional[str] = None,1085+ help: str | None = None,1086 hidden: bool = False,1087 # Choice1088 case_sensitive: bool = True,1089 # Numbers1094- min: Optional[Union[int, float]] = None,1095- max: Optional[Union[int, float]] = None,1090+ min: int | float | None = None,1091+ max: int | float | None = None,1092 clamp: bool = False,1093 # DateTime1098- formats: Optional[list[str]] = None,1094+ formats: list[str] | None = None,1095 # File1100- mode: Optional[str] = None,1101- encoding: Optional[str] = None,1102- errors: Optional[str] = "strict",1103- lazy: Optional[bool] = None,1096+ mode: str | None = None,1097+ encoding: str | None = None,1098+ errors: str | None = "strict",1099+ lazy: bool | None = None,1100 atomic: bool = False,1101 # Path1102 exists: bool = False,1103 file_okay: bool = True,1 unmodified line1105 writable: bool = False,1106 readable: bool = True,1107 resolve_path: bool = False,1108 allow_dash: bool = False,1113- path_type: Union[None, type[str], type[bytes]] = None,1109+ path_type: None | type[str] | type[bytes] = None,1110 # Rich settings1115- rich_help_panel: Union[str, None] = None,1111+ rich_help_panel: str | None = None,1112 ) -> Any: ...1113 1114 1115 def Argument(1116 # Parameter1117 default: Annotated[1122- Optional[Any],1118+ Any | None,1119 Doc(1120 """1121 By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional):1122 15 unmodified lines1138 ),1139 ] = ...,1140 *,1141 callback: Annotated[1146- Optional[Callable[..., Any]],1142+ Callable[..., Any] | None,1143 Doc(1144 """1145 Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal.1146 See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.13 unmodified lines1160 """1161 ),1162 ] = None,1163 metavar: Annotated[1168- Optional[str],1164+ str | None,1165 Doc(1166 """1167 Customize the name displayed in the help text to represent this CLI Argument.1168 By default, it will be the same name you declared, in uppercase.30 unmodified lines1199 """1200 ),1201 ] = False,1202 envvar: Annotated[1207- Optional[Union[str, list[str]]],1203+ str | list[str] | None,1204 Doc(1205 """1206 Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument.1207 For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).9 unmodified lines1217 ),1218 ] = None,1219 # TODO: Remove shell_complete in a future version (after 0.16.0)1220 shell_complete: Annotated[1225- Optional[1226- Callable[1227- [click.Context, click.Parameter, str],1228- Union[list["click.shell_completion.CompletionItem"], list[str]],1229- ]1230- ],1221+ Callable[1222+ [click.Context, click.Parameter, str],1223+ list["click.shell_completion.CompletionItem"] | list[str],1224+ ]1225+ | None,1226 Doc(1227 """1228 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1229 It is however not fully functional, and will likely be removed in future versions.1230 """1231 ),1232 ] = None,1233 autocompletion: Annotated[1239- Optional[Callable[..., Any]],1234+ Callable[..., Any] | None,1235 Doc(1236 """1237 Provide a custom function that helps to autocomplete the values of this CLI Argument.1238 See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.11 unmodified lines1250 """1251 ),1252 ] = None,1253 default_factory: Annotated[1259- Optional[Callable[[], Any]],1254+ Callable[[], Any] | None,1255 Doc(1256 """1257 Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument.1258 11 unmodified lines1270 ),1271 ] = None,1272 # Custom type1273 parser: Annotated[1279- Optional[Callable[[str], Any]],1274+ Callable[[str], Any] | None,1275 Doc(1276 """1277 Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:1278 17 unmodified lines1296 """1297 ),1298 ] = None,1299 click_type: Annotated[1305- Optional[click.ParamType],1300+ click.ParamType | None,1301 Doc(1302 """1303 Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.1304 21 unmodified lines1326 ),1327 ] = None,1328 # TyperArgument1329 show_default: Annotated[1335- Union[bool, str],1330+ bool | str,1331 Doc(1332 """1333 When set to `False`, don't show the default value of this CLI Argument in the [help text](https://typer.tiangolo.com/tutorial/arguments/help/).1334 35 unmodified lines1370 """1371 ),1372 ] = True,1373 help: Annotated[1379- Optional[str],1374+ str | None,1375 Doc(1376 """1377 Help text for this CLI Argument.1378 See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails.53 unmodified lines1432 ),1433 ] = True,1434 # Numbers1435 min: Annotated[1441- Optional[Union[int, float]],1436+ int | float | None,1437 Doc(1438 """1439 For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),1440 you can define numeric validations with `min` and `max` values:13 unmodified lines1454 """1455 ),1456 ] = None,1457 max: Annotated[1463- Optional[Union[int, float]],1458+ int | float | None,1459 Doc(1460 """1461 For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),1462 you can define numeric validations with `min` and `max` values:36 unmodified lines1499 ),1500 ] = False,1501 # DateTime1502 formats: Annotated[1508- Optional[list[str]],1503+ list[str] | None,1504 Doc(1505 """1506 For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),1507 you can customize the formats that can be parsed automatically:18 unmodified lines1526 ),1527 ] = None,1528 # File1529 mode: Annotated[1535- Optional[str],1530+ str | None,1531 Doc(1532 """1533 For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),1534 you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).9 unmodified lines1544 """1545 ),1546 ] = None,1547 encoding: Annotated[1553- Optional[str],1548+ str | None,1549 Doc(1550 """1551 Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).1552 7 unmodified lines1560 """1561 ),1562 ] = None,1563 errors: Annotated[1569- Optional[str],1564+ str | None,1565 Doc(1566 """1567 **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.1568 3 unmodified lines1572 """1573 ),1574 ] = "strict",1575 lazy: Annotated[1581- Optional[bool],1576+ bool | None,1577 Doc(1578 """1579 For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),1580 by default the file will not be created until you actually start writing to it.153 unmodified lines1734 """1735 ),1736 ] = False,1737 path_type: Annotated[1743- Union[None, type[str], type[bytes]],1738+ None | type[str] | type[bytes],1739 Doc(1740 """1741 A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).1742 The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.2 unmodified lines1745 ),1746 ] = None,1747 # Rich settings1748 rich_help_panel: Annotated[1754- Union[str, None],1749+ str | None,1750 Doc(1751 """1752 Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).1753 78 unmodified linesmodified:typer/testing.py+4 added-4 removed
1 from collections.abc import Mapping, Sequence2-from typing import IO, Any, Optional, Union2+from typing import IO, Any3 4 from click.testing import CliRunner as ClickCliRunner # noqa5 from click.testing import Result6 from typer.main import Typer3 unmodified lines10 class CliRunner(ClickCliRunner):11 def invoke( # type: ignore12 self,13 app: Typer,14- args: Optional[Union[str, Sequence[str]]] = None,15- input: Optional[Union[bytes, str, IO[Any]]] = None,16- env: Optional[Mapping[str, Optional[str]]] = None,14+ args: str | Sequence[str] | None = None,15+ input: bytes | str | IO[Any] | None = None,16+ env: Mapping[str, str | None] | None = None,17 catch_exceptions: bool = True,18 color: bool = False,19 **extra: Any,20 ) -> Result:10 unmodified lines