Skip to content
Myr

typing_prompt.py

This file

Path

tests/typing/typing_prompt.py

50 lines · 1.5 KiB · Python

Last changed by

`click.prompt` typing clarifications / improvements (#3407)Rowlando13before adoption5e906a8

History of this file

Take it

`click.prompt` typing clarifications / improvements (#3407)Rowlando13before adoption5e906a8

lines 1–50why, one step back
1from typing_extensions import assert_type
23import 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)