Skip to content
Myr

`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

6 files+105 added−25 removed

modified:src/click/termui.py+58 added-22 removed
1from __future__ import annotations23import builtins4import collections.abc as cabc5import inspect6import io7import itertools
18 unmodified lines
2627if t.TYPE_CHECKING:28 from ._termui_impl import ProgressBar2930 if sys.version_info >= (3, 13):31 from typing import TypeIs32 else:33 from typing_extensions import TypeIs3435V = t.TypeVar("V")36C = t.TypeVar("C")3738# The prompt functions to use. The doc tools currently override these39# functions to customize how they work.40visible_prompt_func: t.Callable[[str], str] = input
73 unmodified lines
114def _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}"132133125def _format_default(default: t.Any) -> t.Any:126 if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127 return default.name134def _format_default(default: V) -> V | str:135 if isinstance(default, (io.IOBase, _LazyFile)):136 name = getattr(default, "name", None)137138 if name is not None:139 return str(name)140141 return default142143144def _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)149150151def 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.165166 If the user aborts the input by sending an interrupt signal, this
21 unmodified lines
188 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): ".191192 .. 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``.196197 .. 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 lines
240241 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)242243 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 lines
modified:src/click/types.py+31 added-3 removed
17 unmodified lines
18from .utils import _LazyFile19from .utils import _safecall20from .utils import format_filename2122# TypeVar(default=...) support.23if sys.version_info >= (3, 13):24 from typing import TypeVar25else:26 from typing_extensions import TypeVar2728if t.TYPE_CHECKING:29 import typing_extensions as te3031 from .core import Context
2 unmodified lines
3435_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)3940_FloatValueT = t.TypeVar("_FloatValueT", bound=float)41_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)42
2 unmodified lines
45 param_type: str46 name: str474842class ParamType(t.Generic[_ValueT_co], abc.ABC):49class 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.5253 To implement a custom type, subclass and implement at least the
13 unmodified lines
67 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.7172 .. 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 """7778 is_composite: t.ClassVar[bool] = False79 arity: int = 1 # read-only
29 unmodified lines
109 name = param_type110111 return {"param_type": param_type, "name": name}112113 @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: ...120121 @t.overload122 def __call__(123 self,124 value: _InputT_contra,125 param: Parameter | None = None,126 ctx: Context | None = None,127 ) -> _ValueT_co: ...128129 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 None
8 unmodified lines
146 .. versionadded:: 2.0147 """148149 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 lines
modified:tests/test_imports.py+2 added
26 unmodified lines
2728ALLOWED_IMPORTS = {29 "__future__",30 "abc",31 "builtins",32 "codecs",33 "collections",34 "collections.abc",35 "configparser",
14 unmodified lines
50 "sys",51 "threading",52 "types",53 "typing",54 "typing_extensions",55 "uuid",56 "weakref",57}58
24 unmodified lines
modified:CHANGES.md+7 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 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`6162## Version 8.4.26364Released 2026-06-24
1561 unmodified lines
modified:pyproject.toml+3 added
12 unmodified lines
13 "Programming Language :: Python",14 "Typing :: Typed",15]16requires-python = ">=3.10"17dependencies = [18 "typing_extensions; python_version < '3.13'",19]2021[project.urls]22Donate = "https://palletsprojects.com/donate"23Documentation = "https://click.palletsprojects.com/"
211 unmodified lines
modified:uv.lock+4 added
173 unmodified lines
174[[package]]175name = "click"176version = "8.5.0.dev0"177source = { editable = "." }178dependencies = [179 { name = "typing-extensions", marker = "python_full_version < '3.13'" },180]181182[package.dev-dependencies]183dev = [184 { name = "ruff" },
35 unmodified lines
220 { name = "pytest" },221]222223[package.metadata]224requires-dist = [{ name = "typing-extensions", marker = "python_full_version < '3.13'" }]225226[package.metadata.requires-dev]227dev = [228 { name = "ruff" },
1437 unmodified lines