Skip to content
Myr

`click.prompt` typing clarifications / improvements (#3407)

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

authored by Rowlando13 · committed by GitHub · parents cfa01ee, 3b16957 · Browse files · 6 files+211 added−18 removed
This commit

State

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

Diff stats

6 files+211 added−18 removed

  • tests:+98 added−0 removed
  • other:+113 added−18 removed

6 files+211 added−18 removed

modified:src/click/termui.py+58 added-15 removed
106 unmodified lines
107def _build_prompt(108 text: str,109 suffix: str,110 show_default: bool | str = False,111 default: t.Any | None = None,111 default: object | None = None,112 show_choices: bool = True,113 type: ParamType[t.Any] | None = None,113 type: object | None = None,114) -> str:115 prompt = text116 if type is not None and show_choices and isinstance(type, Choice):117 prompt += f" ({', '.join(map(str, type.choices))})"118 if isinstance(show_default, str):119 default = f"({show_default})"120 if default is not None and show_default:121 prompt = f"{prompt} [{_format_default(default)}]"122 return f"{prompt}{suffix}"118 default_preview = ""119 if show_default:120 if isinstance(show_default, str):121 default_preview = f" [({show_default})]"122 elif default is not None:123 default_preview = f" [{_format_default(default)}]"124 return f"{prompt}{default_preview}{suffix}"125126125def _format_default(default: t.Any) -> t.Any:126 if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127 return default.name127def _format_default(default: V) -> V | str:128 if isinstance(default, (io.IOBase, _LazyFile)):129 name = getattr(default, "name", None)130131 if name is not None:132 return str(name)133134 return default135136137@t.overload138def prompt(139 text: str,134 default: t.Any | None = None,140 default: str | None = None,141 hide_input: bool = False,142 confirmation_prompt: bool | str = False,137 type: ParamType[t.Any] | t.Any | None = None,138 value_proc: t.Callable[[str], t.Any] | None = None,143 type: None = None,144 value_proc: None = None,145 prompt_suffix: str = ": ",146 show_default: bool | str = True,147 err: bool = False,148 show_choices: bool = True,143) -> t.Any:149) -> str: ...150151152@t.overload153def prompt(154 text: str,155 default: V | str | None = None,156 hide_input: bool = False,157 confirmation_prompt: bool | str = False,158 type: ParamType[V, str] | type[V] | None = None,159 value_proc: t.Callable[[str], V] | None = None,160 prompt_suffix: str = ": ",161 show_default: bool | str = True,162 err: bool = False,163 show_choices: bool = True,164) -> V: ...165166167def prompt(168 text: str,169 default: V | str | None = None,170 hide_input: bool = False,171 confirmation_prompt: bool | str = False,172 type: ParamType[V, str] | type[V] | None = None,173 value_proc: t.Callable[[str], V] | None = None,174 prompt_suffix: str = ": ",175 show_default: bool | str = True,176 err: bool = False,177 show_choices: bool = True,178) -> V:179 """Prompts a user for input. This is a convenience function that can180 be used to prompt a user for input later.181182 If the user aborts the input by sending an interrupt signal, this
21 unmodified lines
204 For example if type is a Choice of either day or week,205 show_choices is true and text is "Group by" then the206 prompt will be "Group by (day, week): ".207208 .. versionchanged:: 8.5.0209 Generically typed: the return type is narrowed by ``type``,210 ``value_proc``, or ``default`` instead of being ``Any``. Runtime211 behavior is unchanged.212213 .. versionchanged:: 8.3.3214 ``show_default`` can be a string to show a custom value instead215 of the actual default, matching the help text behavior.216
44 unmodified lines
261 value = prompt_func(prompt)262 if value:263 break264 elif default is not None:225 value = default265 # Defaults of any type are accepted and round trip through266 # value_proc like typed input, so the annotation is only267 # accurate for typed input.268 value = t.cast("str", default)269 break270 try:271 result = value_proc(value)272 except UsageError as e:
731 unmodified lines
modified:src/click/types.py+50 added-3 removed
28 unmodified lines
29_ValueT = t.TypeVar("_ValueT")30_ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31_ValueT_co = t.TypeVar("_ValueT_co", covariant=True)3233# The input type parameter of ParamType defaults to Any. TypeVar defaults34# (PEP 696) landed in typing on Python 3.13, so type checkers get the35# default from typing_extensions, which is never imported at runtime. On36# older Pythons the runtime TypeVar carries no default;37# ParamType.__class_getitem__ fills in the omitted parameter instead.38if t.TYPE_CHECKING:39 _InputT_contra = te.TypeVar("_InputT_contra", contravariant=True, default=t.Any)40elif sys.version_info >= (3, 13):41 _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True, default=t.Any)42else:43 _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True)4445_FloatValueT = t.TypeVar("_FloatValueT", bound=float)46_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)4748
1 unmodified line
50 param_type: str51 name: str525342class ParamType(t.Generic[_ValueT_co], abc.ABC):54class ParamType(t.Generic[_ValueT_co, _InputT_contra], abc.ABC):55 """Represents the type of a parameter. Validates and converts values56 from the command line or Python into the correct type.5758 To implement a custom type, subclass and implement at least the
13 unmodified lines
72 Now a generic abstract base class. Parameterize with the73 converted value type (``ParamType[int]`` for an integer-returning74 type) so that :meth:`convert` and downstream consumers carry the75 narrowed return type.7677 .. versionchanged:: 8.5.078 Accepts a second optional type parameter for the input value type79 that :meth:`convert` accepts (``ParamType[int, str]`` for a type80 converting strings to integers), defaulting to ``Any``.81 """8283 is_composite: t.ClassVar[bool] = False84 arity: int = 1 # read-only
8 unmodified lines
93 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on94 #: Windows).95 envvar_list_splitter: t.ClassVar[str | None] = None9697 if sys.version_info < (3, 13):98 # ``_InputT_contra`` carries its ``Any`` default only for type99 # checkers: ``TypeVar(default=...)`` (PEP 696) is unavailable at100 # runtime before Python 3.13. Fill in the omitted input type101 # parameter by hand so ``ParamType[int]`` keeps working.102 def __class_getitem__(cls, params: t.Any) -> t.Any:103 if cls is ParamType:104 if not isinstance(params, tuple):105 params = (params,)106 if len(params) == 1:107 params = (*params, t.Any)108 # Checkers cannot see Generic.__class_getitem__ through super().109 return super().__class_getitem__(params) # type: ignore[misc]110111 def to_info_dict(self) -> ParamTypeInfoDict:112 """Gather information that could be useful for a tool generating113 user-facing documentation.114
13 unmodified lines
128 name = param_type129130 return {"param_type": param_type, "name": name}131132 @t.overload133 def __call__(134 self,103 value: t.Any,135 value: None,136 param: Parameter | None = None,137 ctx: Context | None = None,138 ) -> None: ...139140 @t.overload141 def __call__(142 self,143 value: _InputT_contra,144 param: Parameter | None = None,145 ctx: Context | None = None,146 ) -> _ValueT_co: ...147148 def __call__(149 self,150 value: _InputT_contra | None,151 param: Parameter | None = None,152 ctx: Context | None = None,153 ) -> _ValueT_co | None:154 if value is not None:155 return self.convert(value, param, ctx)156 return None
8 unmodified lines
165 .. versionadded:: 2.0166 """167168 def convert(122 self, value: t.Any, param: Parameter | None, ctx: Context | None169 self, value: _InputT_contra, param: Parameter | None, ctx: Context | None170 ) -> _ValueT_co:171 """Convert the value to the correct type. This is not called if172 the value is ``None`` (the missing value).173
1249 unmodified lines
modified:tests/test_utils/test_prompt.py+26 added
12 unmodified lines
13 capfd.readouterr()14 assert isinstance(value, int)151617def test_prompt_default_round_trips_through_type(capfd, monkeypatch):18 """A default that already has the converted value type still passes19 through ``ParamType.convert``, so conversion side effects keep20 applying to defaults."""2122 class DoublingType(click.ParamType[int]):23 name = "doubling"2425 def convert(self, value, param, ctx):26 return int(value) * 22728 monkeypatch.setattr(sys, "stdin", StringIO("\n"))29 value = click.prompt("value", default=5, type=DoublingType())30 capfd.readouterr()31 assert value == 10323334def test_prompt_default_validated_by_type(capfd, monkeypatch):35 """An out-of-range default is rejected by the type's validation and36 prompts again instead of being returned as-is."""37 monkeypatch.setattr(sys, "stdin", StringIO("\n7\n"))38 value = click.prompt("value", default=100, type=click.IntRange(0, 10))39 capfd.readouterr()40 assert value == 7414243@pytest.mark.skipif(WIN, reason="Different behavior on windows.")44def test_prompts_abort(monkeypatch, capsys):45 def f(_):46 raise KeyboardInterrupt()
54 unmodified lines
added:tests/typing/typing_prompt.py+50 added
1from typing_extensions import assert_type23import click45# Without ``type``, ``value_proc``, or a non-``str`` ``default``, the raw6# string input is returned.7assert_type(click.prompt("Name"), str)8assert_type(click.prompt("Name", default="bob"), str)910# The return type is narrowed by the ``type`` argument, whether it is a11# ParamType instance or a plain class, independently of the default's type.12assert_type(click.prompt("Age", type=click.INT), int)13assert_type(click.prompt("Age", type=click.IntRange(0, 130), default=18), int)14assert_type(click.prompt("Age", type=int), int)15assert_type(click.prompt("Age", type=int, default="100"), int)1617# The return type is narrowed by the ``value_proc`` argument.181920def to_float(value: str) -> float:21 return float(value)222324assert_type(click.prompt("Ratio", value_proc=to_float), float)2526# The return type is narrowed by the ``default`` argument alone.27assert_type(click.prompt("Age", default=18), int)282930# A custom type may declare both its converted value and accepted input31# types. Omitting the input type parameter defaults it to ``Any``.32class DoublingType(click.ParamType[int, str]):33 name = "doubling"3435 def convert(36 self, value: str, param: click.Parameter | None, ctx: click.Context | None37 ) -> int:38 return int(value) * 2394041assert_type(click.prompt("Num", type=DoublingType()), int)42assert_type(DoublingType()("21"), int)43assert_type(DoublingType()(None), None)444546class SimpleType(click.ParamType[int]):47 name = "simple"484950assert_type(SimpleType()("21"), int)
modified:tests/test_types.py+22 added
2 unmodified lines
3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click
296 unmodified lines
308def test_choice_get_invalid_choice_message():309 choice = click.Choice(["a", "b", "c"])310 message = choice.get_invalid_choice_message("d", ctx=None)311 assert message == "'d' is not one of 'a', 'b', 'c'."312313314def test_param_type_input_parameter_defaults_at_runtime():315 """Omitting the input type parameter works at runtime on every316 supported Python. The ``Any`` default is native (PEP 696) on Python317 3.13+, and backfilled by ``ParamType.__class_getitem__`` before318 that."""319 assert t.get_args(click.ParamType[int]) == (int, t.Any)320 assert t.get_args(click.ParamType[int, str]) == (int, str)321322323def test_param_type_subclass_omitting_input_parameter():324 class DoublingType(click.ParamType[int]):325 name = "doubling"326327 def convert(self, value, param, ctx):328 return int(value) * 2329330 doubling = DoublingType()331 assert doubling("21") == 42332 assert doubling(None) is None
modified:CHANGES.md+5 added
49 unmodified lines
50 `tmp_path` fixture) with absolute paths instead. For running tests in51 parallel, use process-based isolation (such as `pytest-xdist`) rather52 than threads, since {meth}`CliRunner.invoke` also redirects the53 process-global standard streams. {issue}`3501` {issue}`3700` {pr}`3704`54- `prompt()` is now generically typed and returns the type produced by55 `type`, `value_proc`, or a matching `default` instead of `Any`.56 {class}`ParamType` takes a second optional type parameter describing the57 input value it accepts (`ParamType[int, str]` for a type converting58 strings to integers), defaulting to `Any`. {pr}`3407`5960## Version 8.4.26162Released 2026-06-24
1561 unmodified lines