Skip to content
Myr

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

9 files+174 added−61 removed

modified:src/click/termui.py+45 added-38 removed
1from __future__ import annotations23import builtins3import collections.abc as cabc4import inspect5import io6import itertools
18 unmodified lines
2526if t.TYPE_CHECKING:27 from ._termui_impl import ProgressBar2830 if sys.version_info >= (3, 13):31 from typing import TypeIs32 else:33 from typing_extensions import TypeIs3429V = t.TypeVar("V")36C = t.TypeVar("C")3031# The prompt functions to use. The doc tools currently override these32# functions to customize how they work.33visible_prompt_func: t.Callable[[str], str] = input
99 unmodified lines
133134 return default135136144def _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.overload138def 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: ...150151152@t.overload153def 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: ...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.181
23 unmodified lines
205 show_choices is true and text is "Group by" then the206 prompt will be "Group by (day, week): ".207208 .. 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.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.
40 unmodified lines
256257 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)258259 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 lines
modified:src/click/types.py+26 added-7 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 TypeVar2722if t.TYPE_CHECKING:23 import typing_extensions as te2425 from .core import Context
2 unmodified lines
2829_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)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
44 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
1308 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_imports.py-2 removed
26 unmodified lines
2728ALLOWED_IMPORTS = {29 "__future__",30 "abc",31 "builtins",31 "codecs",32 "collections",33 "collections.abc",34 "configparser",
14 unmodified lines
49 "sys",50 "threading",51 "types",52 "typing",54 "typing_extensions",53 "uuid",54 "weakref",55}56
24 unmodified lines
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-7 removed
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`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
modified:pyproject.toml-3 removed
12 unmodified lines
13 "Programming Language :: Python",14 "Typing :: Typed",15]16requires-python = ">=3.10"17dependencies = [18 "typing_extensions; python_version < '3.13'",19]1718[project.urls]19Donate = "https://palletsprojects.com/donate"20Documentation = "https://click.palletsprojects.com/"
211 unmodified lines
modified:uv.lock-4 removed
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]178179[package.dev-dependencies]180dev = [181 { name = "ruff" },
35 unmodified lines
217 { name = "pytest" },218]219220[package.metadata]224requires-dist = [{ name = "typing-extensions", marker = "python_full_version < '3.13'" }]221222[package.metadata.requires-dev]223dev = [224 { name = "ruff" },
1437 unmodified lines