Make `prompt`/`ParamType` typing work without runtime `typing_extensions`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 0585f45 · Browse files · 9 files·+174 added−61 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+174 added−61 removed
- tests:+98 added−2 removed
- other:+76 added−59 removed
Provenance
- Commit
3b16957- Tree
44e06d6- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
0585f45
9 files changed+174 added−61 removed
modified:src/click/termui.py+45 added-38 removed
1 from __future__ import annotations2 3-import builtins3 import collections.abc as cabc4 import inspect5 import io6 import itertools18 unmodified lines25 26 if t.TYPE_CHECKING:27 from ._termui_impl import ProgressBar28 30- if sys.version_info >= (3, 13):31- from typing import TypeIs32- else:33- from typing_extensions import TypeIs34-29 V = t.TypeVar("V")36-C = t.TypeVar("C")30 31 # The prompt functions to use. The doc tools currently override these32 # functions to customize how they work.33 visible_prompt_func: t.Callable[[str], str] = input99 unmodified lines133 134 return default135 136 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)137+@t.overload138+def prompt(139+ text: str,140+ default: str | None = None,141+ hide_input: bool = False,142+ confirmation_prompt: bool | str = False,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,149+) -> str: ...150 151 152+@t.overload153 def prompt(154 text: str,153- default: V | C | str | None = None,155+ default: V | str | None = None,156 hide_input: bool = False,157 confirmation_prompt: bool | str = False,156- type: ParamType[V, C | str] | V | None = None,157- value_proc: t.Callable[[C | str], V] | None = None,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 23 unmodified lines205 show_choices is true and text is "Group by" then the206 prompt will be "Group by (day, week): ".207 208 .. 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``.209+ 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.40 unmodified lines256 257 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)258 259 while True:244- result: V | None = None260 while True:246- value: C | str = prompt_func(prompt)261+ value = prompt_func(prompt)262 if value:263 break264 elif default is not None:250- if _is_expected_type(default=default, type=type):251- # It's the expected type, don't reparse it.252- result = default253- else:254- # It's not the expected type. Pass it through value_proc before255- # returning.256- value = t.cast("C | str", default)265+ # 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 break258- 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- continue270+ try:271+ result = value_proc(value)272+ except UsageError as e:273+ message = _mask_hidden_input(e.message, value) if hide_input else e.message274+ echo(_("Error: {message}").format(message=message), err=err)275+ continue276 if not confirmation_prompt:277 return result278 while True:279 value2 = prompt_func(confirmation_prompt)724 unmodified linesmodified:src/click/types.py+26 added-7 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-22 if t.TYPE_CHECKING:23 import typing_extensions as te24 25 from .core import Context2 unmodified lines28 29 _ValueT = t.TypeVar("_ValueT")30 _ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)38-_InputT_contra = TypeVar("_InputT_contra", contravariant=True, default=t.Any)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 44 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 1308 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_imports.py-2 removed
26 unmodified lines27 28 ALLOWED_IMPORTS = {29 "__future__",30 "abc",31- "builtins",31 "codecs",32 "collections",33 "collections.abc",34 "configparser",14 unmodified lines49 "sys",50 "threading",51 "types",52 "typing",54- "typing_extensions",53 "uuid",54 "weakref",55 }56 24 unmodified linesmodified: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-7 removed
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`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 linesmodified:pyproject.toml-3 removed
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-]17 18 [project.urls]19 Donate = "https://palletsprojects.com/donate"20 Documentation = "https://click.palletsprojects.com/"211 unmodified linesmodified:uv.lock-4 removed
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-]178 179 [package.dev-dependencies]180 dev = [181 { name = "ruff" },35 unmodified lines217 { name = "pytest" },218 ]219 220 [package.metadata]224-requires-dist = [{ name = "typing-extensions", marker = "python_full_version < '3.13'" }]221 222 [package.metadata.requires-dev]223 dev = [224 { name = "ruff" },1437 unmodified lines