`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
Provenance
- Commit
5e906a8- Tree
44e06d6- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
cfa01ee- Parent 2
3b16957
6 files changed+211 added−18 removed
modified:src/click/termui.py+58 added-15 removed
106 unmodified lines107 def _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}"125 126 125-def _format_default(default: t.Any) -> t.Any:126- if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127- return default.name127+def _format_default(default: V) -> V | str:128+ if isinstance(default, (io.IOBase, _LazyFile)):129+ name = getattr(default, "name", None)130 131+ if name is not None:132+ return str(name)133+134 return default135 136 137+@t.overload138 def 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: ...150+151+152+@t.overload153+def 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: ...165+166+167+def 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.181 182 If the user aborts the input by sending an interrupt signal, this21 unmodified lines204 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): ".207 208+ .. 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.212+213 .. 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 lines261 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 linesmodified:src/click/types.py+50 added-3 removed
28 unmodified lines29 _ValueT = t.TypeVar("_ValueT")30 _ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)32 33+# 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.38+if t.TYPE_CHECKING:39+ _InputT_contra = te.TypeVar("_InputT_contra", contravariant=True, default=t.Any)40+elif sys.version_info >= (3, 13):41+ _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True, default=t.Any)42+else:43+ _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True)44+45 _FloatValueT = t.TypeVar("_FloatValueT", bound=float)46 _FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)47 48 1 unmodified line50 param_type: str51 name: str52 53 42-class ParamType(t.Generic[_ValueT_co], abc.ABC):54+class 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.57 58 To implement a custom type, subclass and implement at least the13 unmodified lines72 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.76+77+ .. 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 """82 83 is_composite: t.ClassVar[bool] = False84 arity: int = 1 # read-only8 unmodified lines93 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on94 #: Windows).95 envvar_list_splitter: t.ClassVar[str | None] = None96 97+ 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]110+111 def to_info_dict(self) -> ParamTypeInfoDict:112 """Gather information that could be useful for a tool generating113 user-facing documentation.114 13 unmodified lines128 name = param_type129 130 return {"param_type": param_type, "name": name}131 132+ @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: ...139+140+ @t.overload141+ def __call__(142+ self,143+ value: _InputT_contra,144+ param: Parameter | None = None,145+ ctx: Context | None = None,146+ ) -> _ValueT_co: ...147+148+ 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 None8 unmodified lines165 .. versionadded:: 2.0166 """167 168 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 linesmodified:tests/test_utils/test_prompt.py+26 added
12 unmodified lines13 capfd.readouterr()14 assert isinstance(value, int)15 16 17+def 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."""21+22+ class DoublingType(click.ParamType[int]):23+ name = "doubling"24+25+ def convert(self, value, param, ctx):26+ return int(value) * 227+28+ monkeypatch.setattr(sys, "stdin", StringIO("\n"))29+ value = click.prompt("value", default=5, type=DoublingType())30+ capfd.readouterr()31+ assert value == 1032+33+34+def 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 == 741+42+43 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")44 def test_prompts_abort(monkeypatch, capsys):45 def f(_):46 raise KeyboardInterrupt()54 unmodified linesadded:tests/typing/typing_prompt.py+50 added
1+from typing_extensions import assert_type2+3+import click4+5+# Without ``type``, ``value_proc``, or a non-``str`` ``default``, the raw6+# string input is returned.7+assert_type(click.prompt("Name"), str)8+assert_type(click.prompt("Name", default="bob"), str)9+10+# 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.12+assert_type(click.prompt("Age", type=click.INT), int)13+assert_type(click.prompt("Age", type=click.IntRange(0, 130), default=18), int)14+assert_type(click.prompt("Age", type=int), int)15+assert_type(click.prompt("Age", type=int, default="100"), int)16+17+# The return type is narrowed by the ``value_proc`` argument.18+19+20+def to_float(value: str) -> float:21+ return float(value)22+23+24+assert_type(click.prompt("Ratio", value_proc=to_float), float)25+26+# The return type is narrowed by the ``default`` argument alone.27+assert_type(click.prompt("Age", default=18), int)28+29+30+# A custom type may declare both its converted value and accepted input31+# types. Omitting the input type parameter defaults it to ``Any``.32+class DoublingType(click.ParamType[int, str]):33+ name = "doubling"34+35+ def convert(36+ self, value: str, param: click.Parameter | None, ctx: click.Context | None37+ ) -> int:38+ return int(value) * 239+40+41+assert_type(click.prompt("Num", type=DoublingType()), int)42+assert_type(DoublingType()("21"), int)43+assert_type(DoublingType()(None), None)44+45+46+class SimpleType(click.ParamType[int]):47+ name = "simple"48+49+50+assert_type(SimpleType()("21"), int)modified:tests/test_types.py+22 added
2 unmodified lines3 import platform4 import subprocess5 import sys6 import tempfile7+import typing as t8 9 import pytest10 11 import click296 unmodified lines308 def 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'."312+313+314+def 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)321+322+323+def test_param_type_subclass_omitting_input_parameter():324+ class DoublingType(click.ParamType[int]):325+ name = "doubling"326+327+ def convert(self, value, param, ctx):328+ return int(value) * 2329+330+ doubling = DoublingType()331+ assert doubling("21") == 42332+ assert doubling(None) is Nonemodified:CHANGES.md+5 added
49 unmodified lines50 `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`59 60 ## Version 8.4.261 62 Released 2026-06-241561 unmodified lines