`click.prompt` typing clarifications / improvements
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andreas Backx · committed by Kevin Deldycke · parent cfa01ee · Browse files · 6 files·+105 added−25 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+105 added−25 removed
- tests:+2 added−0 removed
- other:+103 added−25 removed
Provenance
- Commit
0585f45- Tree
103d61c- Author
Andreas Backx <andreas@backx.org>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
cfa01ee
6 files changed+105 added−25 removed
modified:src/click/termui.py+58 added-22 removed
1 from __future__ import annotations2 3+import builtins4 import collections.abc as cabc5 import inspect6 import io7 import itertools18 unmodified lines26 27 if t.TYPE_CHECKING:28 from ._termui_impl import ProgressBar29 30+ if sys.version_info >= (3, 13):31+ from typing import TypeIs32+ else:33+ from typing_extensions import TypeIs34+35 V = t.TypeVar("V")36+C = t.TypeVar("C")37 38 # The prompt functions to use. The doc tools currently override these39 # functions to customize how they work.40 visible_prompt_func: t.Callable[[str], str] = input73 unmodified lines114 def _build_prompt(115 text: str,116 suffix: str,117 show_default: bool | str = False,111- default: t.Any | None = None,118+ default: object | None = None,119 show_choices: bool = True,113- type: ParamType[t.Any] | None = None,120+ type: object | None = None,121 ) -> str:122 prompt = text123 if type is not None and show_choices and isinstance(type, Choice):124 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}"125+ default_preview = ""126+ if show_default:127+ if isinstance(show_default, str):128+ default_preview = f" [({show_default})]"129+ elif default is not None:130+ default_preview = f" [{_format_default(default)}]"131+ return f"{prompt}{default_preview}{suffix}"132 133 125-def _format_default(default: t.Any) -> t.Any:126- if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127- return default.name134+def _format_default(default: V) -> V | str:135+ if isinstance(default, (io.IOBase, _LazyFile)):136+ name = getattr(default, "name", None)137 138+ if name is not None:139+ return str(name)140+141 return default142 143 144+def _is_expected_type(145+ default: object,146+ type: ParamType[V, t.Any] | V | None,147+) -> TypeIs[V]:148+ return builtins.type(default) is builtins.type(type)149+150+151 def prompt(152 text: str,134- default: t.Any | None = None,153+ default: V | C | str | None = None,154 hide_input: bool = False,155 confirmation_prompt: bool | str = False,137- type: ParamType[t.Any] | t.Any | None = None,138- value_proc: t.Callable[[str], t.Any] | None = None,156+ type: ParamType[V, C | str] | V | None = None,157+ value_proc: t.Callable[[C | str], V] | None = None,158 prompt_suffix: str = ": ",159 show_default: bool | str = True,160 err: bool = False,161 show_choices: bool = True,143-) -> t.Any:162+) -> V:163 """Prompts a user for input. This is a convenience function that can164 be used to prompt a user for input later.165 166 If the user aborts the input by sending an interrupt signal, this21 unmodified lines188 For example if type is a Choice of either day or week,189 show_choices is true and text is "Group by" then the190 prompt will be "Group by (day, week): ".191 192+ .. versionchanged:: 8.5.0193+ ``default`` no longer passes through the ``value_proc`` callback,194+ nor the constructor of the types of ``type`` or ``default`` field,195+ when it is the same type as ``type``.196+197 .. versionchanged:: 8.3.3198 ``show_default`` can be a string to show a custom value instead199 of the actual default, matching the help text behavior.200 39 unmodified lines240 241 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)242 243 while True:244+ result: V | None = None245 while True:221- value = prompt_func(prompt)246+ value: C | str = prompt_func(prompt)247 if value:248 break249 elif default is not None:250+ if _is_expected_type(default=default, type=type):251+ # It's the expected type, don't reparse it.225- value = default252+ result = default253+ else:254+ # It's not the expected type. Pass it through value_proc before255+ # returning.256+ value = t.cast("C | str", default)257 break227- try:228- result = value_proc(value)229- except UsageError as e:230- message = _mask_hidden_input(e.message, value) if hide_input else e.message231- echo(_("Error: {message}").format(message=message), err=err)232- continue258+ if result is None:259+ try:260+ result = t.cast("V", value_proc(value))261+ except UsageError as e:262+ message = (263+ _mask_hidden_input(e.message, t.cast("str", value))264+ if hide_input265+ else e.message266+ )267+ echo(_("Error: {message}").format(message=message), err=err)268+ continue269 if not confirmation_prompt:270 return result271 while True:272 value2 = prompt_func(confirmation_prompt)724 unmodified linesmodified:src/click/types.py+31 added-3 removed
17 unmodified lines18 from .utils import _LazyFile19 from .utils import _safecall20 from .utils import format_filename21 22+# TypeVar(default=...) support.23+if sys.version_info >= (3, 13):24+ from typing import TypeVar25+else:26+ from typing_extensions import TypeVar27+28 if t.TYPE_CHECKING:29 import typing_extensions as te30 31 from .core import Context2 unmodified lines34 35 _ValueT = t.TypeVar("_ValueT")36 _ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)37 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)38+_InputT_contra = TypeVar("_InputT_contra", contravariant=True, default=t.Any)39 40 _FloatValueT = t.TypeVar("_FloatValueT", bound=float)41 _FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)42 2 unmodified lines45 param_type: str46 name: str47 48 42-class ParamType(t.Generic[_ValueT_co], abc.ABC):49+class ParamType(t.Generic[_ValueT_co, _InputT_contra], abc.ABC):50 """Represents the type of a parameter. Validates and converts values51 from the command line or Python into the correct type.52 53 To implement a custom type, subclass and implement at least the13 unmodified lines67 Now a generic abstract base class. Parameterize with the68 converted value type (``ParamType[int]`` for an integer-returning69 type) so that :meth:`convert` and downstream consumers carry the70 narrowed return type.71+72+ .. versionchanged:: 8.5.073+ Accepts a second optional type parameter for the input value type74+ that :meth:`convert` accepts (``ParamType[int, str]`` for a type75+ converting strings to integers), defaulting to ``Any``.76 """77 78 is_composite: t.ClassVar[bool] = False79 arity: int = 1 # read-only29 unmodified lines109 name = param_type110 111 return {"param_type": param_type, "name": name}112 113+ @t.overload114 def __call__(115 self,103- value: t.Any,116+ value: None,117 param: Parameter | None = None,118 ctx: Context | None = None,119+ ) -> None: ...120+121+ @t.overload122+ def __call__(123+ self,124+ value: _InputT_contra,125+ param: Parameter | None = None,126+ ctx: Context | None = None,127+ ) -> _ValueT_co: ...128+129+ def __call__(130+ self,131+ value: _InputT_contra | None,132+ param: Parameter | None = None,133+ ctx: Context | None = None,134 ) -> _ValueT_co | None:135 if value is not None:136 return self.convert(value, param, ctx)137 return None8 unmodified lines146 .. versionadded:: 2.0147 """148 149 def convert(122- self, value: t.Any, param: Parameter | None, ctx: Context | None150+ self, value: _InputT_contra, param: Parameter | None, ctx: Context | None151 ) -> _ValueT_co:152 """Convert the value to the correct type. This is not called if153 the value is ``None`` (the missing value).154 1249 unmodified linesmodified:tests/test_imports.py+2 added
26 unmodified lines27 28 ALLOWED_IMPORTS = {29 "__future__",30 "abc",31+ "builtins",32 "codecs",33 "collections",34 "collections.abc",35 "configparser",14 unmodified lines50 "sys",51 "threading",52 "types",53 "typing",54+ "typing_extensions",55 "uuid",56 "weakref",57 }58 24 unmodified linesmodified:CHANGES.md+7 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 by `type`55+ or `value_proc` instead of `Any`. {class}`ParamType` takes a second optional56+ type parameter describing the input value it accepts (`ParamType[int, str]`57+ for a type converting strings to integers), defaulting to `Any`.58+ Additionally, a `prompt()` default that is already of the expected type is59+ returned as-is instead of doing a round trip through `value_proc` or the60+ type conversion. {pr}`3407`61 62 ## Version 8.4.263 64 Released 2026-06-241561 unmodified linesmodified:pyproject.toml+3 added
12 unmodified lines13 "Programming Language :: Python",14 "Typing :: Typed",15 ]16 requires-python = ">=3.10"17+dependencies = [18+ "typing_extensions; python_version < '3.13'",19+]20 21 [project.urls]22 Donate = "https://palletsprojects.com/donate"23 Documentation = "https://click.palletsprojects.com/"211 unmodified linesmodified:uv.lock+4 added
173 unmodified lines174 [[package]]175 name = "click"176 version = "8.5.0.dev0"177 source = { editable = "." }178+dependencies = [179+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },180+]181 182 [package.dev-dependencies]183 dev = [184 { name = "ruff" },35 unmodified lines220 { name = "pytest" },221 ]222 223 [package.metadata]224+requires-dist = [{ name = "typing-extensions", marker = "python_full_version < '3.13'" }]225 226 [package.metadata.requires-dev]227 dev = [228 { name = "ruff" },1437 unmodified lines