➖ Drop support for Python 3.8 (#1464)
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 76e8462 · Browse files · 24 files·+211 added−231 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Diff stats
24 files+211 added−231 removed
- tests:+39 added−33 removed
- other:+172 added−198 removed
Provenance
- Commit
fbff83e- Tree
b75b384- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
76e8462
24 files changed+211 added−231 removed
modified:scripts/mkdocs_hooks.py+4 added-4 removed
1-from typing import Any, List, Union1+from typing import Any, Union2 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[Union[Page, Section, Link]], *, config: MkDocsConfig11+) -> list[Union[Page, Section, Link]]:12+ new_items: list[Union[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/assets/cli/rich_formatted_app.py+2 added-1 removed
1+from typing import Annotated2+3 import typer2-from typing_extensions import Annotated4 5 app = typer.Typer(rich_markup_mode="rich")6 7 16 unmodified linesmodified:tests/test_ambiguous_params.py+2 added-1 removed
1+from typing import Annotated2+3 import pytest4 import typer5 from typer.testing import CliRunner6 from typer.utils import (2 unmodified lines9 MixedAnnotatedAndDefaultStyleError,10 MultipleTyperAnnotationsError,11 _split_annotation_from_typer_annotations,12 )11-from typing_extensions import Annotated13 14 runner = CliRunner()15 16 216 unmodified linesmodified:tests/test_annotated.py+1 added-1 removed
1 import sys2 from pathlib import Path3+from typing import Annotated4 5 import typer6 from typer.testing import CliRunner6-from typing_extensions import Annotated7 8 from .utils import needs_py3109 10 runner = CliRunner()90 unmodified linesmodified:tests/test_future_annotations.py+2 added-1 removed
1 from __future__ import annotations2 3+from typing import Annotated4+5 import typer6 from typer.testing import CliRunner5-from typing_extensions import Annotated7 8 runner = CliRunner()9 10 17 unmodified linesmodified:tests/test_launch.py+14 added-9 removed
14 unmodified lines15 ("FreeBSD", "xdg-open"),16 ],17 )18 def test_launch_url_unix(system: str, command: str):19- with patch("platform.system", return_value=system), patch(20- "shutil.which", return_value=True21- ), patch("subprocess.Popen") as mock_popen:19+ with (20+ patch("platform.system", return_value=system),21+ patch("shutil.which", return_value=True),22+ patch("subprocess.Popen") as mock_popen,23+ ):24 typer.launch(url)25 26 mock_popen.assert_called_once_with(27 [command, url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT28 )29 30 31 def test_launch_url_windows():30- with patch("platform.system", return_value="Windows"), patch(31- "webbrowser.open"32- ) as mock_webbrowser_open:32+ with (33+ patch("platform.system", return_value="Windows"),34+ patch("webbrowser.open") as mock_webbrowser_open,35+ ):36 typer.launch(url)37 38 mock_webbrowser_open.assert_called_once_with(url)39 40 41 def test_launch_url_no_xdg_open():39- with patch("platform.system", return_value="Linux"), patch(40- "shutil.which", return_value=None41- ), patch("webbrowser.open") as mock_webbrowser_open:42+ with (43+ patch("platform.system", return_value="Linux"),44+ patch("shutil.which", return_value=None),45+ patch("webbrowser.open") as mock_webbrowser_open,46+ ):47 typer.launch(url)48 49 mock_webbrowser_open.assert_called_once_with(url)50 6 unmodified linesmodified:tests/test_others.py+5 added-5 removed
1 unmodified line2 import subprocess3 import sys4 import typing5 from pathlib import Path6+from typing import Annotated7 from unittest import mock8 9 import click10 import pytest3 unmodified lines14 from typer.core import _split_opt15 from typer.main import solve_typer_info_defaults, solve_typer_info_help16 from typer.models import ParameterInfo, TyperInfo17 from typer.testing import CliRunner17-from typing_extensions import Annotated18 19 from .utils import requires_completion_permission20 21 runner = CliRunner()125 unmodified lines147 148 def test_callback_4_list_none():149 app = typer.Typer()150 151- def names_callback(ctx, param, values: typing.Optional[typing.List[str]]):151+ def names_callback(ctx, param, values: typing.Optional[list[str]]):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[typing.List[str]] = typer.Option(158+ names: typing.Optional[list[str]] = typer.Option(159 None, "--name", callback=names_callback160 ),161 ):162 if names is None:8 unmodified lines171 assert "Hello World" in result.stdout172 173 174 def test_empty_list_default_generator():175- def empty_list() -> typing.List[str]:175+ def empty_list() -> list[str]:176 return []177 178 app = typer.Typer()179 180 @app.command()181 def main(182- names: Annotated[typing.List[str], typer.Option(default_factory=empty_list)],182+ names: Annotated[list[str], typer.Option(default_factory=empty_list)],183 ):184 print(names)185 186 result = runner.invoke(app)155 unmodified linesmodified:tests/test_rich_markup_mode.py+5 added-7 removed
1-from typing import List2-1 import pytest2 import typer3 import typer.completion4 from typer.testing import CliRunner50 unmodified lines55 None, ["First line", "", "Line 1", "", "Line 2", "", "Line 3", ""]56 ),57 ],58 )61-def test_markup_mode_newline_pr815(mode: str, lines: List[str]):59+def test_markup_mode_newline_pr815(mode: str, lines: list[str]):60 app = typer.Typer(rich_markup_mode=mode)61 62 @app.command()63 def main(arg: str):29 unmodified lines93 pytest.param("rich", ["First line", "", "Line 1", "Line 2", "Line 3", ""]),94 pytest.param(None, ["First line", "", "Line 1 Line 2 Line 3", ""]),95 ],96 )99-def test_markup_mode_newline_issue447(mode: str, lines: List[str]):97+def test_markup_mode_newline_issue447(mode: str, lines: list[str]):98 app = typer.Typer(rich_markup_mode=mode)99 100 @app.command()101 def main(arg: str):64 unmodified lines166 ],167 ),168 ],169 )172-def test_markup_mode_newline_mixed(mode: str, lines: List[str]):170+def test_markup_mode_newline_mixed(mode: str, lines: list[str]):171 app = typer.Typer(rich_markup_mode=mode)172 173 @app.command()174 def main(arg: str):35 unmodified lines210 pytest.param("rich", ["First line", "", "- 1", "- 2", "- 3", ""]),211 pytest.param(None, ["First line", "", "- 1 - 2 - 3", ""]),212 ],213 )216-def test_markup_mode_bullets_single_newline(mode: str, lines: List[str]):214+def test_markup_mode_bullets_single_newline(mode: str, lines: list[str]):215 app = typer.Typer(rich_markup_mode=mode)216 217 @app.command()218 def main(arg: str):34 unmodified lines253 ),254 (None, ["First line", "", "- 1", "", "- 2", "", "- 3", ""]),255 ],256 )259-def test_markup_mode_bullets_double_newline(mode: str, lines: List[str]):257+def test_markup_mode_bullets_double_newline(mode: str, lines: list[str]):258 app = typer.Typer(rich_markup_mode=mode)259 260 @app.command()261 def main(arg: str):29 unmodified linesmodified:tests/test_type_conversion.py+8 added-8 removed
1 from enum import Enum2 from pathlib import Path3-from typing import Any, List, Optional, Tuple3+from typing import Any, Optional4 5 import click6 import pytest7 import typer46 unmodified lines54 def test_optional_tuple():55 app = typer.Typer()56 57 @app.command()58- def opt(number: Optional[Tuple[int, int]] = None):58+ def opt(number: Optional[tuple[int, int]] = None):59 if number:60 print(f"Number: {number}")61 else:62 print("No number")26 unmodified lines89 90 91 @pytest.mark.parametrize(92 "type_annotation",93- [List[Path], List[SomeEnum], List[str]],93+ [list[Path], list[SomeEnum], list[str]],94 )95 def test_list_parameters_convert_to_lists(type_annotation):96 # Lists containing objects that are converted by Click (i.e. not Path or Enum)97 # should not be inadvertently converted to tuples12 unmodified lines110 111 @pytest.mark.parametrize(112 "type_annotation",113 [114- Tuple[str, str],115- Tuple[str, Path],116- Tuple[Path, Path],117- Tuple[str, SomeEnum],118- Tuple[SomeEnum, SomeEnum],114+ tuple[str, str],115+ tuple[str, Path],116+ tuple[Path, Path],117+ tuple[str, SomeEnum],118+ tuple[SomeEnum, SomeEnum],119 ],120 )121 def test_tuple_parameter_elements_are_converted_recursively(type_annotation):122 # Tuple elements that aren't converted by Click (i.e. Path or Enum)49 unmodified linesmodified:typer/_completion_classes.py+9 added-9 removed
1 import importlib.util2 import os3 import re4 import sys5-from typing import Any, Dict, List, Tuple5+from typing import Any6 7 import click8 import click.parser9 import click.shell_completion27 unmodified lines37 class BashComplete(click.shell_completion.BashComplete):38 name = Shells.bash.value39 source_template = COMPLETION_SCRIPT_BASH40 41- def source_vars(self) -> Dict[str, Any]:41+ def source_vars(self) -> dict[str, Any]:42 return {43 "complete_func": self.func_name,44 "autocomplete_var": self.complete_var,45 "prog_name": self.prog_name,46 }47 48- def get_completion_args(self) -> Tuple[List[str], str]:48+ def get_completion_args(self) -> tuple[list[str], str]:49 cwords = click_split_arg_string(os.environ["COMP_WORDS"])50 cword = int(os.environ["COMP_CWORD"])51 args = cwords[1:cword]52 20 unmodified lines73 class ZshComplete(click.shell_completion.ZshComplete):74 name = Shells.zsh.value75 source_template = COMPLETION_SCRIPT_ZSH76 77- def source_vars(self) -> Dict[str, Any]:77+ def source_vars(self) -> dict[str, Any]:78 return {79 "complete_func": self.func_name,80 "autocomplete_var": self.complete_var,81 "prog_name": self.prog_name,82 }83 84- def get_completion_args(self) -> Tuple[List[str], str]:84+ def get_completion_args(self) -> tuple[list[str], str]:85 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")86 cwords = click_split_arg_string(completion_args)87 args = cwords[1:]88 if args and not completion_args.endswith(" "):35 unmodified lines124 class FishComplete(click.shell_completion.FishComplete):125 name = Shells.fish.value126 source_template = COMPLETION_SCRIPT_FISH127 128- def source_vars(self) -> Dict[str, Any]:128+ def source_vars(self) -> dict[str, Any]:129 return {130 "complete_func": self.func_name,131 "autocomplete_var": self.complete_var,132 "prog_name": self.prog_name,133 }134 135- def get_completion_args(self) -> Tuple[List[str], str]:135+ def get_completion_args(self) -> tuple[list[str], str]:136 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")137 cwords = click_split_arg_string(completion_args)138 args = cwords[1:]139 if args and not completion_args.endswith(" "):37 unmodified lines177 class PowerShellComplete(click.shell_completion.ShellComplete):178 name = Shells.powershell.value179 source_template = COMPLETION_SCRIPT_POWER_SHELL180 181- def source_vars(self) -> Dict[str, Any]:181+ def source_vars(self) -> dict[str, Any]:182 return {183 "complete_func": self.func_name,184 "autocomplete_var": self.complete_var,185 "prog_name": self.prog_name,186 }187 188- def get_completion_args(self) -> Tuple[List[str], str]:188+ def get_completion_args(self) -> tuple[list[str], str]:189 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")190 incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")191 cwords = click_split_arg_string(completion_args)192 args = cwords[1:-1] if incomplete else cwords[1:]14 unmodified linesmodified:typer/_completion_shared.py+2 added-2 removed
1 unmodified line2 import re3 import subprocess4 from enum import Enum5 from pathlib import Path6-from typing import Optional, Tuple, Union6+from typing import Optional, Union7 8 import click9 from typer.core import HAS_SHELLINGHAM10 194 unmodified lines205 def install(206 shell: Optional[str] = None,207 prog_name: Optional[str] = None,208 complete_var: Optional[str] = None,209-) -> Tuple[str, Path]:209+) -> tuple[str, Path]:210 prog_name = prog_name or click.get_current_context().find_root().info_name211 assert prog_name212 if complete_var is None:213 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())46 unmodified linesmodified:typer/_typing.py+7 added-9 removed
8 unmodified lines9 Any,10 Callable,11 Literal,12 Optional,13- Tuple,14- Type,13 Union,14 get_args,15 get_origin,16 get_type_hints,17 )18 19 if sys.version_info < (3, 10):20 23- def is_union(tp: Optional[Type[Any]]) -> bool:21+ def is_union(tp: Optional[type[Any]]) -> bool:22 return tp is Union23 24 else:25 import types26 29- def is_union(tp: Optional[Type[Any]]) -> bool:27+ def is_union(tp: Optional[type[Any]]) -> bool:28 return tp is Union or tp is types.UnionType # noqa: E72129 30 31 __all__ = (13 unmodified lines45 46 NoneType = None.__class__47 48 51-NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None])49+NONE_TYPES: tuple[Any, Any, Any] = (None, NoneType, Literal[None])50 51 52 def is_none_type(type_: Any) -> bool:53 for none_type in NONE_TYPES:1 unmodified line55 return True56 return False57 58 61-def is_callable_type(type_: Type[Any]) -> bool:59+def is_callable_type(type_: type[Any]) -> bool:60 return type_ is Callable or get_origin(type_) is Callable61 62 65-def is_literal_type(type_: Type[Any]) -> bool:63+def is_literal_type(type_: type[Any]) -> bool:64 import typing_extensions65 66 return get_origin(type_) in (Literal, typing_extensions.Literal)67 68 71-def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:69+def literal_values(type_: type[Any]) -> tuple[Any, ...]:70 return get_args(type_)71 72 75-def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]:73+def all_literal_values(type_: type[Any]) -> tuple[Any, ...]:74 """75 This method is used to retrieve all Literal values as76 Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)77 e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`6 unmodified linesmodified:typer/cli.py+2 added-2 removed
1 import importlib.util2 import re3 import sys4 from pathlib import Path5-from typing import Any, List, Optional5+from typing import Any, Optional6 7 import click8 import typer9 import typer.core42 unmodified lines52 state.func = func_name53 54 55 class TyperCLIGroup(typer.core.TyperGroup):56- def list_commands(self, ctx: click.Context) -> List[str]:56+ 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]:248 unmodified linesmodified:typer/completion.py+3 added-2 removed
1 import os2 import sys3-from typing import Any, MutableMapping, Tuple3+from collections.abc import MutableMapping4+from typing import Any5 6 import click7 8 from ._completion_classes import completion_init5 unmodified lines14 15 _click_patched = False16 17 17-def get_completion_inspect_parameters() -> Tuple[ParamMeta, ParamMeta]:18+def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]:19 completion_init()20 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")21 if HAS_SHELLINGHAM and not test_disable_detection:22 parameters = get_params_from_function(_install_completion_placeholder_function)125 unmodified linesmodified:typer/core.py+21 added-25 removed
1 unmodified line2 import importlib.util3 import inspect4 import os5 import sys6+from collections.abc import MutableMapping, Sequence7 from difflib import get_close_matches8 from enum import Enum9 from gettext import gettext as _10 from typing import (11 Any,12 Callable,12- Dict,13- List,14- MutableMapping,13 Optional,16- Sequence,14 TextIO,18- Tuple,15 Union,16 cast,17 )18 17 unmodified lines36 DEFAULT_MARKUP_MODE = None37 38 39 # Copy from click.parser._split_opt44-def _split_opt(opt: str) -> Tuple[str, str]:40+def _split_opt(opt: str) -> tuple[str, str]:41 first = opt[:1]42 if first.isalnum():43 return "", opt44 if opt[1:2] == first:4 unmodified lines49 def _typer_param_setup_autocompletion_compat(50 self: click.Parameter,51 *,52 autocompletion: Optional[57- Callable[[click.Context, List[str], str], List[Union[Tuple[str, str], str]]]53+ Callable[[click.Context, list[str], str], list[Union[tuple[str, str], str]]]54 ] = None,55 ) -> None:56 if self._custom_shell_complete is not None:57 import warnings8 unmodified lines66 if autocompletion is not None:67 68 def compat_autocompletion(69 ctx: click.Context, param: click.core.Parameter, incomplete: str74- ) -> List["click.shell_completion.CompletionItem"]:70+ ) -> list["click.shell_completion.CompletionItem"]:71 from click.shell_completion import CompletionItem72 73 out = []74 16 unmodified lines91 obj: Union["TyperArgument", "TyperOption"],92 *,93 ctx: click.Context,94 show_default_is_str: bool,99- default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],95+ default_value: Union[list[Any], tuple[Any, ...], str, Callable[..., Any], Any],96 ) -> str:97 # Extracted from click.core.Option.get_help_record() to be reused by98 # rich_utils avoiding RegEx hacks99 if show_default_is_str:152 unmodified lines252 def __init__(253 self,254 *,255 # Parameter260- param_decls: List[str],256+ param_decls: list[str],257 type: Optional[Any] = None,258 required: Optional[bool] = None,259 default: Optional[Any] = None,260 callback: Optional[Callable[..., Any]] = None,261 nargs: Optional[int] = None,262 metavar: Optional[str] = None,263 expose_value: bool = True,264 is_eager: bool = False,269- envvar: Optional[Union[str, List[str]]] = None,265+ envvar: Optional[Union[str, list[str]]] = None,266 # Note that shell_complete is not fully supported and will be removed in future versions267 # TODO: Remove shell_complete in a future version (after 0.16.0)268 shell_complete: Optional[269 Callable[270 [click.Context, click.Parameter, str],275- Union[List["click.shell_completion.CompletionItem"], List[str]],271+ Union[list["click.shell_completion.CompletionItem"], list[str]],272 ]273 ] = None,274 autocompletion: Optional[Callable[..., Any]] = None,275 # TyperArgument31 unmodified lines307 self,308 *,309 ctx: click.Context,310 show_default_is_str: bool,315- default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],311+ default_value: Union[list[Any], tuple[Any, ...], str, Callable[..., Any], Any],312 ) -> str:313 return _get_default_string(314 self,315 ctx=ctx,5 unmodified lines321 self, *, ctx: click.Context322 ) -> Optional[Union[Any, Callable[[], Any]]]:323 return _extract_default_help_str(self, ctx=ctx)324 329- def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:325+ def get_help_record(self, ctx: click.Context) -> Optional[tuple[str, str]]:326 # Modified version of click.core.Option.get_help_record()327 # to support Arguments328 if self.hidden:329 return None80 unmodified lines410 def __init__(411 self,412 *,413 # Parameter418- param_decls: List[str],414+ param_decls: list[str],415 type: Optional[Union[click.types.ParamType, Any]] = None,416 required: Optional[bool] = None,417 default: Optional[Any] = None,418 callback: Optional[Callable[..., Any]] = None,419 nargs: Optional[int] = None,420 metavar: Optional[str] = None,421 expose_value: bool = True,422 is_eager: bool = False,427- envvar: Optional[Union[str, List[str]]] = None,423+ envvar: Optional[Union[str, list[str]]] = None,424 # Note that shell_complete is not fully supported and will be removed in future versions425 # TODO: Remove shell_complete in a future version (after 0.16.0)426 shell_complete: Optional[427 Callable[428 [click.Context, click.Parameter, str],433- Union[List["click.shell_completion.CompletionItem"], List[str]],429+ Union[list["click.shell_completion.CompletionItem"], list[str]],430 ]431 ] = None,432 autocompletion: Optional[Callable[..., Any]] = None,433 # Option46 unmodified lines480 self,481 *,482 ctx: click.Context,483 show_default_is_str: bool,488- default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],484+ default_value: Union[list[Any], tuple[Any, ...], str, Callable[..., Any], Any],485 ) -> str:486 return _get_default_string(487 self,488 ctx=ctx,13 unmodified lines502 return super().make_metavar(ctx=ctx) # type: ignore[arg-type]503 # Click < 8.2504 return super().make_metavar() # type: ignore[call-arg]505 510- def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:506+ def get_help_record(self, ctx: click.Context) -> Optional[tuple[str, str]]:507 # Duplicate all of Click's logic only to modify a single line, to allow boolean508 # flags with only names for False values as it's currently supported by Typer509 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false510 if self.hidden:148 unmodified lines659 def __init__(660 self,661 name: Optional[str],662 *,667- context_settings: Optional[Dict[str, Any]] = None,663+ context_settings: Optional[dict[str, Any]] = None,664 callback: Optional[Callable[..., Any]] = None,669- params: Optional[List[click.Parameter]] = None,665+ params: Optional[list[click.Parameter]] = None,666 help: Optional[str] = None,667 epilog: Optional[str] = None,668 short_help: Optional[str] = None,669 options_metavar: Optional[str] = "[OPTIONS]",74 unmodified lines744 self,745 *,746 name: Optional[str] = None,747 commands: Optional[752- Union[Dict[str, click.Command], Sequence[click.Command]]748+ Union[dict[str, click.Command], Sequence[click.Command]]749 ] = None,750 # Rich settings751 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,752 rich_help_panel: Union[str, None] = None,21 unmodified lines774 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var775 )776 777 def resolve_command(782- self, ctx: click.Context, args: List[str]783- ) -> Tuple[Optional[str], Optional[click.Command], List[str]]:778+ self, ctx: click.Context, args: list[str]779+ ) -> tuple[Optional[str], Optional[click.Command], list[str]]:780 try:781 return super().resolve_command(ctx, args)782 except click.UsageError as e:783 if self.suggest_commands:37 unmodified lines821 ctx=ctx,822 markup_mode=self.rich_markup_mode,823 )824 829- def list_commands(self, ctx: click.Context) -> List[str]:825+ def list_commands(self, ctx: click.Context) -> list[str]:826 """Returns a list of subcommand names.827 Note that in Click's Group class, these are sorted.828 In Typer, we wish to maintain the original order of creation (cf Issue #933)"""829 return [n for n, c in self.commands.items()]modified:typer/main.py+35 added-34 removed
3 unmodified lines4 import shutil5 import subprocess6 import sys7 import traceback8+from collections.abc import 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 TracebackType14-from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union15+from typing import Any, Callable, Optional, Union16 from uuid import UUID17 18 import click19 from typer._types import TyperChoice35 unmodified lines55 _typer_developer_exception_attr_name = "__typer_developer_exception__"56 57 58 def except_hook(58- exc_type: Type[BaseException], exc_value: BaseException, tb: Optional[TracebackType]59+ exc_type: type[BaseException], exc_value: BaseException, tb: Optional[TracebackType]60 ) -> None:61 exception_config: Union[DeveloperExceptionConfig, None] = getattr(62 exc_value, _typer_developer_exception_attr_name, None63 )18 unmodified lines82 console_stderr = rich_utils._get_rich_console(stderr=True)83 console_stderr.print(rich_tb)84 return85 tb_exc = traceback.TracebackException.from_exception(exc)85- stack: List[FrameSummary] = []86+ stack: list[FrameSummary] = []87 for frame in tb_exc.stack:88 if any(frame.filename.startswith(path) for path in internal_dir_names):89 if not exception_config.pretty_exceptions_short:90 # Hide the line for internal libraries, Typer and Click14 unmodified lines105 print(line, file=sys.stderr)106 return107 108 108-def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:109+def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]:110 install_param, show_param = get_completion_inspect_parameters()111 click_install_param, _ = get_click_param(install_param)112 click_show_param, _ = get_click_param(show_param)113 return click_install_param, click_show_param3 unmodified lines117 def __init__(118 self,119 *,120 name: Optional[str] = Default(None),120- cls: Optional[Type[TyperGroup]] = Default(None),121+ cls: Optional[type[TyperGroup]] = Default(None),122 invoke_without_command: bool = Default(False),123 no_args_is_help: bool = Default(False),124 subcommand_metavar: Optional[str] = Default(None),125 chain: bool = Default(False),126 result_callback: Optional[Callable[..., Any]] = Default(None),127 # Command127- context_settings: Optional[Dict[Any, Any]] = Default(None),128+ context_settings: Optional[dict[Any, Any]] = Default(None),129 callback: Optional[Callable[..., Any]] = Default(None),130 help: Optional[str] = Default(None),131 epilog: Optional[str] = Default(None),132 short_help: Optional[str] = Default(None),34 unmodified lines167 add_help_option=add_help_option,168 hidden=hidden,169 deprecated=deprecated,170 )170- self.registered_groups: List[TyperInfo] = []171- self.registered_commands: List[CommandInfo] = []171+ self.registered_groups: list[TyperInfo] = []172+ self.registered_commands: list[CommandInfo] = []173 self.registered_callback: Optional[TyperInfo] = None174 175 def callback(176 self,177 *,177- cls: Optional[Type[TyperGroup]] = Default(None),178+ cls: Optional[type[TyperGroup]] = Default(None),179 invoke_without_command: bool = Default(False),180 no_args_is_help: bool = Default(False),181 subcommand_metavar: Optional[str] = Default(None),182 chain: bool = Default(False),183 result_callback: Optional[Callable[..., Any]] = Default(None),184 # Command184- context_settings: Optional[Dict[Any, Any]] = Default(None),185+ context_settings: Optional[dict[Any, Any]] = Default(None),186 help: Optional[str] = Default(None),187 epilog: Optional[str] = Default(None),188 short_help: Optional[str] = Default(None),189 options_metavar: Optional[str] = Default(None),31 unmodified lines221 def command(222 self,223 name: Optional[str] = None,224 *,224- cls: Optional[Type[TyperCommand]] = None,225- context_settings: Optional[Dict[Any, Any]] = None,225+ cls: Optional[type[TyperCommand]] = None,226+ context_settings: Optional[dict[Any, Any]] = None,227 help: Optional[str] = None,228 epilog: Optional[str] = None,229 short_help: Optional[str] = None,230 options_metavar: Optional[str] = None,36 unmodified lines267 self,268 typer_instance: "Typer",269 *,270 name: Optional[str] = Default(None),270- cls: Optional[Type[TyperGroup]] = Default(None),271+ cls: Optional[type[TyperGroup]] = Default(None),272 invoke_without_command: bool = Default(False),273 no_args_is_help: bool = Default(False),274 subcommand_metavar: Optional[str] = Default(None),275 chain: bool = Default(False),276 result_callback: Optional[Callable[..., Any]] = Default(None),277 # Command277- context_settings: Optional[Dict[Any, Any]] = Default(None),278+ context_settings: Optional[dict[Any, Any]] = Default(None),279 callback: Optional[Callable[..., Any]] = Default(None),280 help: Optional[str] = Default(None),281 epilog: Optional[str] = Default(None),282 short_help: Optional[str] = Default(None),152 unmodified lines435 return typer_info.help.value436 437 438 def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:438- values: Dict[str, Any] = {}439+ values: dict[str, Any] = {}440 for name, value in typer_info.__dict__.items():441 # Priority 1: Value was set in app.add_typer()442 if not isinstance(value, DefaultPlaceholder):443 values[name] = value35 unmodified lines479 ) -> TyperGroup:480 assert group_info.typer_instance, (481 "A Typer instance is needed to generate a Click Group"482 )482- commands: Dict[str, click.Command] = {}483+ commands: dict[str, click.Command] = {}484 for command_info in group_info.typer_instance.registered_commands:485 command = get_command_from_info(486 command_info=command_info,487 pretty_exceptions_short=pretty_exceptions_short,65 unmodified lines553 554 555 def get_params_convertors_ctx_param_name_from_function(556 callback: Optional[Callable[..., Any]],556-) -> Tuple[List[Union[click.Argument, click.Option]], Dict[str, Any], Optional[str]]:557+) -> tuple[list[Union[click.Argument, click.Option]], dict[str, Any], Optional[str]]:558 params = []559 convertors = {}560 context_param_name = None561 if callback:70 unmodified lines632 return value if isinstance(value, Path) else Path(value)633 return None634 635 635-def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:636+def generate_enum_convertor(enum: type[Enum]) -> Callable[[Any], Any]:637 val_map = {str(val.value): val for val in enum}638 639 def convertor(value: Any) -> Any:640 if value is not None:6 unmodified lines647 648 649 def generate_list_convertor(650 convertor: Optional[Callable[[Any], Any]], default_value: Optional[Any]650-) -> Callable[[Optional[Sequence[Any]]], Optional[List[Any]]]:651- def internal_convertor(value: Optional[Sequence[Any]]) -> Optional[List[Any]]:651+) -> Callable[[Optional[Sequence[Any]]], Optional[list[Any]]]:652+ def internal_convertor(value: Optional[Sequence[Any]]) -> Optional[list[Any]]:653 if (value is None) or (default_value is None and len(value) == 0):654 return None655 return [convertor(v) if convertor else v for v in value]656 1 unmodified line658 659 660 def generate_tuple_convertor(661 types: Sequence[Any],661-) -> Callable[[Optional[Tuple[Any, ...]]], Optional[Tuple[Any, ...]]]:662+) -> Callable[[Optional[tuple[Any, ...]]], Optional[tuple[Any, ...]]]:663 convertors = [determine_type_convertor(type_) for type_ in types]664 665 def internal_convertor(665- param_args: Optional[Tuple[Any, ...]],666- ) -> Optional[Tuple[Any, ...]]:666+ param_args: Optional[tuple[Any, ...]],667+ ) -> Optional[tuple[Any, ...]]:668 if param_args is None:669 return None670 return tuple(671 convertor(arg) if convertor else arg6 unmodified lines678 def get_callback(679 *,680 callback: Optional[Callable[..., Any]] = None,681 params: Sequence[click.Parameter] = [],681- convertors: Optional[Dict[str, Callable[[str], Any]]] = None,682+ convertors: Optional[dict[str, Callable[[str], Any]]] = None,683 context_param_name: Optional[str] = None,684 pretty_exceptions_short: bool,685 ) -> Optional[Callable[..., Any]]:686 use_convertors = convertors or {}687 if not callback:688 return None689 parameters = get_params_from_function(callback)689- use_params: Dict[str, Any] = {}690+ use_params: dict[str, Any] = {}691 for param_name in parameters:692 use_params[param_name] = None693 for param in params:694 if param.name:117 unmodified lines812 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover813 814 815 def lenient_issubclass(815- cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]816+ cls: Any, class_or_tuple: Union[AnyType, tuple[AnyType, ...]]817 ) -> bool:818 return isinstance(cls, type) and issubclass(cls, class_or_tuple)819 820 821 def get_click_param(822 param: ParamMeta,822-) -> Tuple[Union[click.Argument, click.Option], Any]:823+) -> tuple[Union[click.Argument, click.Option], Any]:824 # First, find out what will be:825 # * ParamInfo (ArgumentInfo or OptionInfo)826 # * default_value827 # * required34 unmodified lines862 assert len(types) == 1, "Typer Currently doesn't support Union types"863 main_type = types[0]864 origin = get_origin(main_type)865 # Handle Tuples and Lists865- if lenient_issubclass(origin, List):866+ if lenient_issubclass(origin, list):867 main_type = get_args(main_type)[0]868 assert not get_origin(main_type), (869 "List types with complex sub-types are not currently supported"870 )871 is_list = True871- elif lenient_issubclass(origin, Tuple): # type: ignore872+ elif lenient_issubclass(origin, tuple):873 types = []874 for type_ in get_args(main_type):875 assert not get_origin(type_), (876 "Tuple types with complex sub-types are not currently supported"114 unmodified lines991 parameters = get_params_from_function(callback)992 ctx_name = None993 click_param_name = None994 value_name = None994- untyped_names: List[str] = []995+ untyped_names: list[str] = []996 for param_name, param_sig in parameters.items():997 if lenient_issubclass(param_sig.annotation, click.Context):998 ctx_name = param_name999 elif lenient_issubclass(param_sig.annotation, click.Parameter):15 unmodified lines1015 "Too many CLI parameter callback function parameters"1016 )1017 1018 def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:1018- use_params: Dict[str, Any] = {}1019+ use_params: dict[str, Any] = {}1020 if ctx_name:1021 use_params[ctx_name] = ctx1022 if click_param_name:1023 use_params[click_param_name] = param23 unmodified lines1047 origin = get_origin(param_sig.annotation)1048 if lenient_issubclass(param_sig.annotation, click.Context):1049 ctx_name = param_sig.name1050 unassigned_params.remove(param_sig)1050- elif lenient_issubclass(origin, List):1051+ elif lenient_issubclass(origin, list):1052 args_name = param_sig.name1053 unassigned_params.remove(param_sig)1054 elif lenient_issubclass(param_sig.annotation, str):1055 incomplete_name = param_sig.name15 unmodified lines1071 raise click.ClickException(1072 f"Invalid autocompletion callback parameters: {show_params}"1073 )1074 1074- def wrapper(ctx: click.Context, args: List[str], incomplete: Optional[str]) -> Any:1075- use_params: Dict[str, Any] = {}1075+ def wrapper(ctx: click.Context, args: list[str], incomplete: Optional[str]) -> Any:1076+ use_params: dict[str, Any] = {}1077 if ctx_name:1078 use_params[ctx_name] = ctx1079 if args_name:1080 use_params[args_name] = args77 unmodified linesmodified:typer/models.py+19 added-22 removed
1 import inspect2 import io3+from collections.abc import Sequence4 from typing import (5 TYPE_CHECKING,6 Any,7 Callable,7- Dict,8- List,8 Optional,10- Sequence,11- Type,9 TypeVar,10 Union,11 )12 6 unmodified lines19 20 21 NoneType = type(None)22 26-AnyType = Type[Any]23+AnyType = type[Any]24 25 Required = ...26 27 55 unmodified lines83 def __init__(84 self,85 name: Optional[str] = None,86 *,90- cls: Optional[Type["TyperCommand"]] = None,91- context_settings: Optional[Dict[Any, Any]] = None,87+ cls: Optional[type["TyperCommand"]] = None,88+ context_settings: Optional[dict[Any, Any]] = None,89 callback: Optional[Callable[..., Any]] = None,90 help: Optional[str] = None,91 epilog: Optional[str] = None,92 short_help: Optional[str] = None,26 unmodified lines119 self,120 typer_instance: Optional["Typer"] = Default(None),121 *,122 name: Optional[str] = Default(None),126- cls: Optional[Type["TyperGroup"]] = Default(None),123+ cls: Optional[type["TyperGroup"]] = Default(None),124 invoke_without_command: bool = Default(False),125 no_args_is_help: bool = Default(False),126 subcommand_metavar: Optional[str] = Default(None),127 chain: bool = Default(False),128 result_callback: Optional[Callable[..., Any]] = Default(None),129 # Command133- context_settings: Optional[Dict[Any, Any]] = Default(None),130+ context_settings: Optional[dict[Any, Any]] = Default(None),131 callback: Optional[Callable[..., Any]] = Default(None),132 help: Optional[str] = Default(None),133 epilog: Optional[str] = Default(None),134 short_help: Optional[str] = Default(None),33 unmodified lines168 callback: Optional[Callable[..., Any]] = None,169 metavar: Optional[str] = None,170 expose_value: bool = True,171 is_eager: bool = False,175- envvar: Optional[Union[str, List[str]]] = None,172+ envvar: Optional[Union[str, list[str]]] = None,173 # Note that shell_complete is not fully supported and will be removed in future versions174 # TODO: Remove shell_complete in a future version (after 0.16.0)175 shell_complete: Optional[176 Callable[177 [click.Context, click.Parameter, str],181- Union[List["click.shell_completion.CompletionItem"], List[str]],178+ Union[list["click.shell_completion.CompletionItem"], list[str]],179 ]180 ] = None,181 autocompletion: Optional[Callable[..., Any]] = None,182 default_factory: Optional[Callable[[], Any]] = None,12 unmodified lines195 min: Optional[Union[int, float]] = None,196 max: Optional[Union[int, float]] = None,197 clamp: bool = False,198 # DateTime202- formats: Optional[List[str]] = None,199+ formats: Optional[list[str]] = None,200 # File201 mode: Optional[str] = None,202 encoding: Optional[str] = None,203 errors: Optional[str] = "strict",6 unmodified lines210 writable: bool = False,211 readable: bool = True,212 resolve_path: bool = False,213 allow_dash: bool = False,217- path_type: Union[None, Type[str], Type[bytes]] = None,214+ path_type: Union[None, type[str], type[bytes]] = None,215 # Rich settings216 rich_help_panel: Union[str, None] = None,217 ):218 # Check if user has provided multiple custom parsers59 unmodified lines278 callback: Optional[Callable[..., Any]] = None,279 metavar: Optional[str] = None,280 expose_value: bool = True,281 is_eager: bool = False,285- envvar: Optional[Union[str, List[str]]] = None,282+ envvar: Optional[Union[str, list[str]]] = None,283 # Note that shell_complete is not fully supported and will be removed in future versions284 # TODO: Remove shell_complete in a future version (after 0.16.0)285 shell_complete: Optional[286 Callable[287 [click.Context, click.Parameter, str],291- Union[List["click.shell_completion.CompletionItem"], List[str]],288+ Union[list["click.shell_completion.CompletionItem"], list[str]],289 ]290 ] = None,291 autocompletion: Optional[Callable[..., Any]] = None,292 default_factory: Optional[Callable[[], Any]] = None,21 unmodified lines314 min: Optional[Union[int, float]] = None,315 max: Optional[Union[int, float]] = None,316 clamp: bool = False,317 # DateTime321- formats: Optional[List[str]] = None,318+ formats: Optional[list[str]] = None,319 # File320 mode: Optional[str] = None,321 encoding: Optional[str] = None,322 errors: Optional[str] = "strict",6 unmodified lines329 writable: bool = False,330 readable: bool = True,331 resolve_path: bool = False,332 allow_dash: bool = False,336- path_type: Union[None, Type[str], Type[bytes]] = None,333+ path_type: Union[None, type[str], type[bytes]] = None,334 # Rich settings335 rich_help_panel: Union[str, None] = None,336 ):337 super().__init__(69 unmodified lines407 callback: Optional[Callable[..., Any]] = None,408 metavar: Optional[str] = None,409 expose_value: bool = True,410 is_eager: bool = False,414- envvar: Optional[Union[str, List[str]]] = None,411+ envvar: Optional[Union[str, list[str]]] = None,412 # Note that shell_complete is not fully supported and will be removed in future versions413 # TODO: Remove shell_complete in a future version (after 0.16.0)414 shell_complete: Optional[415 Callable[416 [click.Context, click.Parameter, str],420- Union[List["click.shell_completion.CompletionItem"], List[str]],417+ Union[list["click.shell_completion.CompletionItem"], list[str]],418 ]419 ] = None,420 autocompletion: Optional[Callable[..., Any]] = None,421 default_factory: Optional[Callable[[], Any]] = None,12 unmodified lines434 min: Optional[Union[int, float]] = None,435 max: Optional[Union[int, float]] = None,436 clamp: bool = False,437 # DateTime441- formats: Optional[List[str]] = None,438+ formats: Optional[list[str]] = None,439 # File440 mode: Optional[str] = None,441 encoding: Optional[str] = None,442 errors: Optional[str] = "strict",6 unmodified lines449 writable: bool = False,450 readable: bool = True,451 resolve_path: bool = False,452 allow_dash: bool = False,456- path_type: Union[None, Type[str], Type[bytes]] = None,453+ path_type: Union[None, type[str], type[bytes]] = None,454 # Rich settings455 rich_help_panel: Union[str, None] = None,456 ):457 super().__init__(75 unmodified lines533 class TyperPath(click.Path):534 # Overwrite Click's behaviour to be compatible with Typer's autocompletion system535 def shell_complete(536 self, ctx: click.Context, param: click.Parameter, incomplete: str540- ) -> List[click.shell_completion.CompletionItem]:537+ ) -> list[click.shell_completion.CompletionItem]:538 """Return an empty list so that the autocompletion functionality539 will work properly from the commandline.540 """541 return []modified:typer/params.py+25 added-25 removed
1-from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, overload1+from typing import TYPE_CHECKING, Any, Callable, Optional, Union, overload2 3 import click4 5 from .models import ArgumentInfo, OptionInfo11 unmodified lines17 callback: Optional[Callable[..., Any]] = None,18 metavar: Optional[str] = None,19 expose_value: bool = True,20 is_eager: bool = False,21- envvar: Optional[Union[str, List[str]]] = None,21+ envvar: Optional[Union[str, list[str]]] = None,22 # Note that shell_complete is not fully supported and will be removed in future versions23 # TODO: Remove shell_complete in a future version (after 0.16.0)24 shell_complete: Optional[25 Callable[26 [click.Context, click.Parameter, str],27- Union[List["click.shell_completion.CompletionItem"], List[str]],27+ Union[list["click.shell_completion.CompletionItem"], list[str]],28 ]29 ] = None,30 autocompletion: Optional[Callable[..., Any]] = None,31 default_factory: Optional[Callable[[], Any]] = None,20 unmodified lines52 min: Optional[Union[int, float]] = None,53 max: Optional[Union[int, float]] = None,54 clamp: bool = False,55 # DateTime56- formats: Optional[List[str]] = None,56+ formats: Optional[list[str]] = None,57 # File58 mode: Optional[str] = None,59 encoding: Optional[str] = None,60 errors: Optional[str] = "strict",6 unmodified lines67 writable: bool = False,68 readable: bool = True,69 resolve_path: bool = False,70 allow_dash: bool = False,71- path_type: Union[None, Type[str], Type[bytes]] = None,71+ path_type: Union[None, type[str], type[bytes]] = None,72 # Rich settings73 rich_help_panel: Union[str, None] = None,74 ) -> Any: ...75 7 unmodified lines83 callback: Optional[Callable[..., Any]] = None,84 metavar: Optional[str] = None,85 expose_value: bool = True,86 is_eager: bool = False,87- envvar: Optional[Union[str, List[str]]] = None,87+ envvar: Optional[Union[str, list[str]]] = None,88 # Note that shell_complete is not fully supported and will be removed in future versions89 # TODO: Remove shell_complete in a future version (after 0.16.0)90 shell_complete: Optional[91 Callable[92 [click.Context, click.Parameter, str],93- Union[List["click.shell_completion.CompletionItem"], List[str]],93+ Union[list["click.shell_completion.CompletionItem"], list[str]],94 ]95 ] = None,96 autocompletion: Optional[Callable[..., Any]] = None,97 default_factory: Optional[Callable[[], Any]] = None,20 unmodified lines118 min: Optional[Union[int, float]] = None,119 max: Optional[Union[int, float]] = None,120 clamp: bool = False,121 # DateTime122- formats: Optional[List[str]] = None,122+ formats: Optional[list[str]] = None,123 # File124 mode: Optional[str] = None,125 encoding: Optional[str] = None,126 errors: Optional[str] = "strict",6 unmodified lines133 writable: bool = False,134 readable: bool = True,135 resolve_path: bool = False,136 allow_dash: bool = False,137- path_type: Union[None, Type[str], Type[bytes]] = None,137+ path_type: Union[None, type[str], type[bytes]] = None,138 # Rich settings139 rich_help_panel: Union[str, None] = None,140 ) -> Any: ...141 5 unmodified lines147 callback: Optional[Callable[..., Any]] = None,148 metavar: Optional[str] = None,149 expose_value: bool = True,150 is_eager: bool = False,151- envvar: Optional[Union[str, List[str]]] = None,151+ envvar: Optional[Union[str, list[str]]] = None,152 # Note that shell_complete is not fully supported and will be removed in future versions153 # TODO: Remove shell_complete in a future version (after 0.16.0)154 shell_complete: Optional[155 Callable[156 [click.Context, click.Parameter, str],157- Union[List["click.shell_completion.CompletionItem"], List[str]],157+ Union[list["click.shell_completion.CompletionItem"], list[str]],158 ]159 ] = None,160 autocompletion: Optional[Callable[..., Any]] = None,161 default_factory: Optional[Callable[[], Any]] = None,21 unmodified lines183 min: Optional[Union[int, float]] = None,184 max: Optional[Union[int, float]] = None,185 clamp: bool = False,186 # DateTime187- formats: Optional[List[str]] = None,187+ formats: Optional[list[str]] = None,188 # File189 mode: Optional[str] = None,190 encoding: Optional[str] = None,191 errors: Optional[str] = "strict",6 unmodified lines198 writable: bool = False,199 readable: bool = True,200 resolve_path: bool = False,201 allow_dash: bool = False,202- path_type: Union[None, Type[str], Type[bytes]] = None,202+ path_type: Union[None, type[str], type[bytes]] = None,203 # Rich settings204 rich_help_panel: Union[str, None] = None,205 ) -> Any:206 return OptionInfo(62 unmodified lines269 callback: Optional[Callable[..., Any]] = None,270 metavar: Optional[str] = None,271 expose_value: bool = True,272 is_eager: bool = False,273- envvar: Optional[Union[str, List[str]]] = None,273+ envvar: Optional[Union[str, list[str]]] = None,274 # Note that shell_complete is not fully supported and will be removed in future versions275 # TODO: Remove shell_complete in a future version (after 0.16.0)276 shell_complete: Optional[277 Callable[278 [click.Context, click.Parameter, str],279- Union[List["click.shell_completion.CompletionItem"], List[str]],279+ Union[list["click.shell_completion.CompletionItem"], list[str]],280 ]281 ] = None,282 autocompletion: Optional[Callable[..., Any]] = None,283 default_factory: Optional[Callable[[], Any]] = None,11 unmodified lines295 min: Optional[Union[int, float]] = None,296 max: Optional[Union[int, float]] = None,297 clamp: bool = False,298 # DateTime299- formats: Optional[List[str]] = None,299+ formats: Optional[list[str]] = None,300 # File301 mode: Optional[str] = None,302 encoding: Optional[str] = None,303 errors: Optional[str] = "strict",6 unmodified lines310 writable: bool = False,311 readable: bool = True,312 resolve_path: bool = False,313 allow_dash: bool = False,314- path_type: Union[None, Type[str], Type[bytes]] = None,314+ path_type: Union[None, type[str], type[bytes]] = None,315 # Rich settings316 rich_help_panel: Union[str, None] = None,317 ) -> Any: ...318 7 unmodified lines326 callback: Optional[Callable[..., Any]] = None,327 metavar: Optional[str] = None,328 expose_value: bool = True,329 is_eager: bool = False,330- envvar: Optional[Union[str, List[str]]] = None,330+ envvar: Optional[Union[str, list[str]]] = None,331 # Note that shell_complete is not fully supported and will be removed in future versions332 # TODO: Remove shell_complete in a future version (after 0.16.0)333 shell_complete: Optional[334 Callable[335 [click.Context, click.Parameter, str],336- Union[List["click.shell_completion.CompletionItem"], List[str]],336+ Union[list["click.shell_completion.CompletionItem"], list[str]],337 ]338 ] = None,339 autocompletion: Optional[Callable[..., Any]] = None,340 default_factory: Optional[Callable[[], Any]] = None,11 unmodified lines352 min: Optional[Union[int, float]] = None,353 max: Optional[Union[int, float]] = None,354 clamp: bool = False,355 # DateTime356- formats: Optional[List[str]] = None,356+ formats: Optional[list[str]] = None,357 # File358 mode: Optional[str] = None,359 encoding: Optional[str] = None,360 errors: Optional[str] = "strict",6 unmodified lines367 writable: bool = False,368 readable: bool = True,369 resolve_path: bool = False,370 allow_dash: bool = False,371- path_type: Union[None, Type[str], Type[bytes]] = None,371+ path_type: Union[None, type[str], type[bytes]] = None,372 # Rich settings373 rich_help_panel: Union[str, None] = None,374 ) -> Any: ...375 5 unmodified lines381 callback: Optional[Callable[..., Any]] = None,382 metavar: Optional[str] = None,383 expose_value: bool = True,384 is_eager: bool = False,385- envvar: Optional[Union[str, List[str]]] = None,385+ envvar: Optional[Union[str, list[str]]] = None,386 # Note that shell_complete is not fully supported and will be removed in future versions387 # TODO: Remove shell_complete in a future version (after 0.16.0)388 shell_complete: Optional[389 Callable[390 [click.Context, click.Parameter, str],391- Union[List["click.shell_completion.CompletionItem"], List[str]],391+ Union[list["click.shell_completion.CompletionItem"], list[str]],392 ]393 ] = None,394 autocompletion: Optional[Callable[..., Any]] = None,395 default_factory: Optional[Callable[[], Any]] = None,12 unmodified lines408 min: Optional[Union[int, float]] = None,409 max: Optional[Union[int, float]] = None,410 clamp: bool = False,411 # DateTime412- formats: Optional[List[str]] = None,412+ formats: Optional[list[str]] = None,413 # File414 mode: Optional[str] = None,415 encoding: Optional[str] = None,416 errors: Optional[str] = "strict",6 unmodified lines423 writable: bool = False,424 readable: bool = True,425 resolve_path: bool = False,426 allow_dash: bool = False,427- path_type: Union[None, Type[str], Type[bytes]] = None,427+ path_type: Union[None, type[str], type[bytes]] = None,428 # Rich settings429 rich_help_panel: Union[str, None] = None,430 ) -> Any:431 return ArgumentInfo(48 unmodified linesmodified:typer/rich_utils.py+16 added-15 removed
1 unmodified line2 3 import inspect4 import io5 from collections import defaultdict6+from collections.abc import Iterable7 from gettext import gettext as _8 from os import getenv8-from typing import Any, DefaultDict, Dict, Iterable, List, Literal, Optional, Union9+from typing import Any, Literal, Optional, Union10 11 import click12 from rich import box13 from rich.align import Align212 unmodified lines226 """227 # import here to avoid cyclic imports228 from .core import TyperArgument, TyperOption229 229- items: List[Union[Text, Markdown]] = []230+ items: list[Union[Text, Markdown]] = []231 232 # Get the environment variable first233 234 envvar = getattr(param, "envvar", None)94 unmodified lines329 330 def _print_options_panel(331 *,332 name: str,332- params: Union[List[click.Option], List[click.Argument]],333+ params: Union[list[click.Option], list[click.Argument]],334 ctx: click.Context,335 markup_mode: MarkupModeStrict,336 console: Console,337 ) -> None:337- options_rows: List[List[RenderableType]] = []338- required_rows: List[Union[str, Text]] = []338+ options_rows: list[list[RenderableType]] = []339+ required_rows: list[Union[str, Text]] = []340 for param in params:341 # Short and long form342 opt_long_strs = []343 opt_short_strs = []73 unmodified lines417 markup_mode=markup_mode,418 ),419 ]420 )420- rows_with_required: List[List[RenderableType]] = []421+ rows_with_required: list[list[RenderableType]] = []422 if any(required_rows):423 for required, row in zip(required_rows, options_rows):424 rows_with_required.append([required, *row])425 else:426 rows_with_required = options_rows427 if options_rows:427- t_styles: Dict[str, Any] = {428+ t_styles: dict[str, Any] = {429 "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,430 "leading": STYLE_OPTIONS_TABLE_LEADING,431 "box": STYLE_OPTIONS_TABLE_BOX,432 "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,24 unmodified lines457 458 def _print_commands_panel(459 *,460 name: str,460- commands: List[click.Command],461+ commands: list[click.Command],462 markup_mode: MarkupModeStrict,463 console: Console,464 cmd_len: int,465 ) -> None:465- t_styles: Dict[str, Any] = {466+ t_styles: dict[str, Any] = {467 "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,468 "leading": STYLE_COMMANDS_TABLE_LEADING,469 "box": STYLE_COMMANDS_TABLE_BOX,470 "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,21 unmodified lines492 # A big ratio makes the description column be greedy and take all the space493 # available instead of allowing the command column to grow and misalign with494 # other panels.495 commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10)495- rows: List[List[Union[RenderableType, None]]] = []496- deprecated_rows: List[Union[RenderableType, None]] = []496+ rows: list[list[Union[RenderableType, None]]] = []497+ deprecated_rows: list[Union[RenderableType, None]] = []498 for command in commands:499 helptext = command.short_help or command.help or ""500 command_name = command.name or ""501 if command.deprecated:64 unmodified lines566 ),567 (0, 1, 1, 1),568 )569 )569- panel_to_arguments: DefaultDict[str, List[click.Argument]] = defaultdict(list)570- panel_to_options: DefaultDict[str, List[click.Option]] = defaultdict(list)570+ panel_to_arguments: defaultdict[str, list[click.Argument]] = defaultdict(list)571+ panel_to_options: defaultdict[str, list[click.Option]] = defaultdict(list)572 for param in obj.get_params(ctx):573 # Skip if option is hidden574 if getattr(param, "hidden", False):575 continue46 unmodified lines622 console=console,623 )624 625 if isinstance(obj, click.Group):625- panel_to_commands: DefaultDict[str, List[click.Command]] = defaultdict(list)626+ panel_to_commands: defaultdict[str, list[click.Command]] = defaultdict(list)627 for command_name in obj.list_commands(ctx):628 command = obj.get_command(ctx, command_name)629 if command and not command.hidden:630 panel_name = (107 unmodified lines738 739 def get_traceback(740 exc: BaseException,741 exception_config: DeveloperExceptionConfig,741- internal_dir_names: List[str],742+ internal_dir_names: list[str],743 ) -> Traceback:744 rich_tb = Traceback.from_exception(745 type(exc),746 exc,6 unmodified linesmodified:typer/testing.py+2 added-1 removed
1-from typing import IO, Any, Mapping, Optional, Sequence, Union1+from collections.abc import Mapping, Sequence2+from typing import IO, Any, Optional, Union3 4 from click.testing import CliRunner as ClickCliRunner # noqa5 from click.testing import Result6 from typer.main import Typer24 unmodified linesmodified:typer/utils.py+13 added-13 removed
1 import inspect2 import sys3 from copy import copy4-from typing import Any, Callable, Dict, List, Tuple, Type, cast4+from typing import Any, Callable, cast5 6 from ._typing import Annotated, get_args, get_origin, get_type_hints7 from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta8 9 10-def _param_type_to_user_string(param_type: Type[ParameterInfo]) -> str:10+def _param_type_to_user_string(param_type: type[ParameterInfo]) -> str:11 # Render a `ParameterInfo` subclass for use in error messages.12 # User code doesn't call `*Info` directly, so errors should present the classes how13 # they were (probably) defined in the user code.14 if param_type is OptionInfo:5 unmodified lines20 21 22 class AnnotatedParamWithDefaultValueError(Exception):23 argument_name: str24- param_type: Type[ParameterInfo]24+ param_type: type[ParameterInfo]25 26- def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):26+ def __init__(self, argument_name: str, param_type: type[ParameterInfo]):27 self.argument_name = argument_name28 self.param_type = param_type29 30 def __str__(self) -> str:5 unmodified lines36 37 38 class MixedAnnotatedAndDefaultStyleError(Exception):39 argument_name: str40- annotated_param_type: Type[ParameterInfo]41- default_param_type: Type[ParameterInfo]40+ annotated_param_type: type[ParameterInfo]41+ default_param_type: type[ParameterInfo]42 43 def __init__(44 self,45 argument_name: str,46- annotated_param_type: Type[ParameterInfo],47- default_param_type: Type[ParameterInfo],46+ annotated_param_type: type[ParameterInfo],47+ default_param_type: type[ParameterInfo],48 ):49 self.argument_name = argument_name50 self.annotated_param_type = annotated_param_type51 self.default_param_type = default_param_type24 unmodified lines76 77 78 class DefaultFactoryAndDefaultValueError(Exception):79 argument_name: str80- param_type: Type[ParameterInfo]80+ param_type: type[ParameterInfo]81 82- def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):82+ def __init__(self, argument_name: str, param_type: type[ParameterInfo]):83 self.argument_name = argument_name84 self.param_type = param_type85 86 def __str__(self) -> str:4 unmodified lines91 )92 93 94 def _split_annotation_from_typer_annotations(95- base_annotation: Type[Any],96-) -> Tuple[Type[Any], List[ParameterInfo]]:95+ base_annotation: type[Any],96+) -> tuple[type[Any], list[ParameterInfo]]:97 if get_origin(base_annotation) is not Annotated:98 return base_annotation, []99 base_annotation, *maybe_typer_annotations = get_args(base_annotation)100 return base_annotation, [2 unmodified lines103 if isinstance(annotation, ParameterInfo)104 ]105 106 107-def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:107+def get_params_from_function(func: Callable[..., Any]) -> dict[str, ParamMeta]:108 if sys.version_info >= (3, 10):109 signature = inspect.signature(func, eval_str=True)110 else:111 signature = inspect.signature(func)79 unmodified linesmodified:pdm_build.py+8 added-8 removed
1 import os2-from typing import Any, Dict, List2+from typing import Any3 4 from pdm.backend.hooks import Context5 6 TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "typer")3 unmodified lines10 metadata = context.config.metadata11 # Get main version12 version = metadata["version"]13 # Get package names to keep in sync with the same main version14- sync_dependencies: List[str] = context.config.data["tool"]["tiangolo"][14+ sync_dependencies: list[str] = context.config.data["tool"]["tiangolo"][15 "_internal-slim-build"16 ]["sync-dependencies"]17 # Get custom config for the current package, from the env var18- config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][18+ config: dict[str, Any] = context.config.data["tool"]["tiangolo"][19 "_internal-slim-build"20 ]["packages"][TIANGOLO_BUILD_PACKAGE]21- project_config: Dict[str, Any] = config["project"]21+ project_config: dict[str, Any] = config["project"]22 # Get main optional dependencies, extras23- optional_dependencies: Dict[str, List[str]] = metadata.get(23+ optional_dependencies: dict[str, list[str]] = metadata.get(24 "optional-dependencies", {}25 )26 # Get custom optional dependencies name to always include in this (non-slim) package27- include_optional_dependencies: List[str] = config.get(27+ include_optional_dependencies: list[str] = config.get(28 "include-optional-dependencies", []29 )30 # Override main [project] configs with custom configs for this package31 for key, value in project_config.items():32 metadata[key] = value33 # Get custom build config for the current package34- build_config: Dict[str, Any] = (34+ build_config: dict[str, Any] = (35 config.get("tool", {}).get("pdm", {}).get("build", {})36 )37 # Override PDM build config with custom build config for this package38 for key, value in build_config.items():39 context.config.build_config[key] = value40 # Get main dependencies41- dependencies: List[str] = metadata.get("dependencies", [])41+ dependencies: list[str] = metadata.get("dependencies", [])42 # Add optional dependencies to the default dependencies for this (non-slim) package43 for include_optional in include_optional_dependencies:44 optional_dependencies_group = optional_dependencies.get(include_optional, [])45 dependencies.extend(optional_dependencies_group)10 unmodified linesmodified:pyproject.toml+1 added-2 removed
9 unmodified lines10 description = "Typer, build great CLIs. Easy to code. Based on Python type hints."11 authors = [12 {name = "Sebastián Ramírez", email = "tiangolo@gmail.com"},13 ]14-requires-python = ">=3.8"14+requires-python = ">=3.9"15 classifiers = [16 "Intended Audience :: Information Technology",17 "Intended Audience :: System Administrators",18 "Operating System :: OS Independent",6 unmodified lines25 "Typing :: Typed",26 "Development Status :: 4 - Beta",27 "Intended Audience :: Developers",28 "Programming Language :: Python :: 3 :: Only",29- "Programming Language :: Python :: 3.8",29 "Programming Language :: Python :: 3.9",30 "Programming Language :: Python :: 3.10",31 "Programming Language :: Python :: 3.11",32 "Programming Language :: Python :: 3.12",216 unmodified linesmodified:uv.lock+5 added-25 removed
1 version = 12 revision = 33-requires-python = ">=3.8"3+requires-python = ">=3.9"4 resolution-markers = [5 "python_full_version >= '3.10'",6- "python_full_version == '3.9.*'",7- "python_full_version < '3.9'",6+ "python_full_version < '3.10'",7 ]8 9 [[package]]10 name = "click"11 version = "8.1.8"12 source = { registry = "https://pypi.org/simple" }13 resolution-markers = [15- "python_full_version == '3.9.*'",16- "python_full_version < '3.9'",14+ "python_full_version < '3.10'",15 ]16 dependencies = [17 { name = "colorama", marker = "python_full_version < '3.10' and sys_platform == 'win32'" },18 ]30 unmodified lines49 name = "markdown-it-py"50 version = "3.0.0"51 source = { registry = "https://pypi.org/simple" }52 resolution-markers = [55- "python_full_version == '3.9.*'",56- "python_full_version < '3.9'",53+ "python_full_version < '3.10'",54 ]55 dependencies = [56 { name = "mdurl", marker = "python_full_version < '3.10'" },57 ]65 unmodified lines123 { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },124 { name = "click", version = "8.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },125 { name = "rich" },126 { name = "shellingham" },130- { name = "typing-extensions", version = "4.13.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" },131- { name = "typing-extensions", version = "4.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.9'" },127+ { name = "typing-extensions" },128 ]129 130 [package.metadata]131 requires-dist = [4 unmodified lines136 ]137 138 [[package]]139 name = "typing-extensions"144-version = "4.13.2"145-source = { registry = "https://pypi.org/simple" }146-resolution-markers = [147- "python_full_version < '3.9'",148-]149-sdist = { url = "https://files.pythonhosted.org/packages/f6/37/23083fcd6e35492953e8d2aaaa68b860eb422b34627b13f2ce3eb6106061/typing_extensions-4.13.2.tar.gz", hash = "sha256:e6c81219bd689f51865d9e372991c540bda33a0379d5573cddb9a3a23f7caaef", size = 106967, upload-time = "2025-04-10T14:19:05.416Z" }150-wheels = [151- { url = "https://files.pythonhosted.org/packages/8b/54/b1ae86c0973cc6f0210b53d508ca3641fb6d0c56823f288d108bc7ab3cc8/typing_extensions-4.13.2-py3-none-any.whl", hash = "sha256:a439e7c04b49fec3e5d3e2beaa21755cadbbdc391694e28ccdd36ca4a1408f8c", size = 45806, upload-time = "2025-04-10T14:19:03.967Z" },152-]153-154-[[package]]155-name = "typing-extensions"140 version = "4.15.0"141 source = { registry = "https://pypi.org/simple" }158-resolution-markers = [159- "python_full_version >= '3.10'",160- "python_full_version == '3.9.*'",161-]142 sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" }143 wheels = [144 { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },145 ]