Skip to content
Myr

Expand `Choice` token normalization + make generic (#2796)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Andreas Backx · committed by GitHub · parent 8a47580 · Browse files · 10 files+238 added−70 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+238 added−70 removed

  • tests:+113 added−9 removed
  • other:+125 added−61 removed

10 files+238 added−70 removed

modified:docs/options.rst+14 added-6 removed
373 unmodified lines
374In that case you can use :class:`Choice` type. It can be instantiated375with a list of valid values. The originally passed choice will be returned,376not the str passed on the command line. Token normalization functions and377``case_sensitive=False`` can cause the two to be different but still match.378:meth:`Choice.normalize_choice` for more info.379380Example:381382.. click:example::383384 import enum385386 class HashType(enum.Enum):387 MD5 = 'MD5'388 SHA1 = 'SHA1'389390 @click.command()391 @click.option('--hash-type',385 type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))386 def digest(hash_type):392 type=click.Choice(HashType, case_sensitive=False))393 def digest(hash_type: HashType):394 click.echo(hash_type)395396What it looks like:397
6 unmodified lines
404 invoke(digest, args=['--hash-type=foo'])405 println()406 invoke(digest, args=['--help'])407401Only pass the choices as list or tuple. Other iterables (like402generators) may lead to unexpected results.408Since version 8.2.0 any iterable may be passed to :class:`Choice`, here409an ``Enum`` is used which will result in all enum values to be valid410choices.411412Choices work with options that have ``multiple=True``. If a ``default``413value is given with ``multiple=True``, it should be a list or tuple of414valid choices.415408Choices should be unique after considering the effects of409``case_sensitive`` and any specified token normalization function.416Choices should be unique after normalization, see417:meth:`Choice.normalize_choice` for more info.418419.. versionchanged:: 7.1420 The resulting value from an option will always be one of the421 originally passed choices regardless of ``case_sensitive``.
514 unmodified lines
modified:src/click/core.py+7 added-7 removed
2190 unmodified lines
2191 same as the name for options, but the metavar for arguments.2192 """2193 return self.name # type: ignore21942195 def make_metavar(self) -> str:2195 def make_metavar(self, ctx: Context) -> str:2196 if self.metavar is not None:2197 return self.metavar21982199 metavar = self.type.get_metavar(self)2199 metavar = self.type.get_metavar(param=self, ctx=ctx)22002201 if metavar is None:2202 metavar = self.type.name.upper()2203
570 unmodified lines
2774 if any_slashes:2775 any_prefix_is_slash = True27762777 if not self.is_flag and not self.count:2778 rv += f" {self.make_metavar()}"2778 rv += f" {self.make_metavar(ctx=ctx)}"27792780 return rv27812782 rv = [_write_opts(self.opts)]
272 unmodified lines
3055 if self.metavar is not None:3056 return self.metavar3057 return self.name.upper() # type: ignore30583059 def make_metavar(self) -> str:3059 def make_metavar(self, ctx: Context) -> str:3060 if self.metavar is not None:3061 return self.metavar3062 var = self.type.get_metavar(self)3062 var = self.type.get_metavar(param=self, ctx=ctx)3063 if not var:3064 var = self.name.upper() # type: ignore3065 if self.deprecated:3066 var += "!"
20 unmodified lines
3087 )3088 return name, [arg], []30893090 def get_usage_pieces(self, ctx: Context) -> list[str]:3091 return [self.make_metavar()]3091 return [self.make_metavar(ctx)]30923093 def get_error_hint(self, ctx: Context) -> str:3094 return f"'{self.make_metavar()}'"3094 return f"'{self.make_metavar(ctx)}'"30953096 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3097 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)3098
23 unmodified lines
modified:src/click/exceptions.py+3 added-1 removed
172 unmodified lines
173 param_type = self.param.param_type_name174175 msg = self.message176 if self.param is not None:177 msg_extra = self.param.type.get_missing_message(self.param)177 msg_extra = self.param.type.get_missing_message(178 param=self.param, ctx=self.ctx179 )180 if msg_extra:181 if msg:182 msg += f". {msg_extra}"183 else:
125 unmodified lines
modified:src/click/types.py+96 added-45 removed
1from __future__ import annotations23import collections.abc as cabc4import enum5import os6import stat7import sys8import typing as t
14 unmodified lines
23 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem2627ParamTypeValue = t.TypeVar("ParamTypeValue")282930class ParamType:31 """Represents the type of a parameter. Validates and converts values32 from the command line or Python into the correct type.33
54 unmodified lines
88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)9189 def get_metavar(self, param: Parameter) -> str | None:92 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:93 """Returns the metavar default for this param if it provides one."""9492 def get_missing_message(self, param: Parameter) -> str | None:95 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:96 """Optionally might return extra information about a missing97 parameter.9899 .. versionadded:: 2.0
129 unmodified lines
229 def __repr__(self) -> str:230 return "STRING"231232230class Choice(ParamType):233class Choice(ParamType, t.Generic[ParamTypeValue]):234 """The choice type allows a value to be checked against a fixed set232 of supported values. All of these values have to be strings.235 of supported values.236234 You should only pass a list or tuple of choices. Other iterables235 (like generators) may lead to surprising results.237 You may pass any iterable value which will be converted to a tuple238 and thus will only be iterated once.239237 The resulting value will always be one of the originally passed choices238 regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``239 being specified.240 The resulting value will always be one of the originally passed choices.241 See :meth:`normalize_choice` for more info on the mapping of strings242 to choices. See :ref:`choice-opts` for an example.243241 See :ref:`choice-opts` for an example.242244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.246247 .. versionchanged:: 8.2.0248 Non-``str`` ``choices`` are now supported. It can additionally be any249 iterable. Before you were not recommended to pass anything but a list or250 tuple.251252 .. versionadded:: 8.2.0253 Choice normalization can be overridden via :meth:`normalize_choice`.254 """255256 name = "choice"257258 def __init__(250 self, choices: cabc.Sequence[str], case_sensitive: bool = True259 self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True260 ) -> None:252 self.choices = choices261 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)262 self.case_sensitive = case_sensitive263264 def to_info_dict(self) -> dict[str, t.Any]:265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict269270 def _normalized_mapping(271 self, ctx: Context | None = None272 ) -> cabc.Mapping[ParamTypeValue, str]:273 """274 Returns mapping where keys are the original choices and the values are275 the normalized values that are accepted via the command line.276277 This is a simple wrapper around :meth:`normalize_choice`, use that278 instead which is supported.279 """280 return {281 choice: self.normalize_choice(282 choice=choice,283 ctx=ctx,284 )285 for choice in self.choices286 }287288 def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:289 """290 Normalize a choice value, used to map a passed string to a choice.291 Each choice must have a unique normalized value.292293 By default uses :meth:`Context.token_normalize_func` and if not case294 sensitive, convert it to a casefolded value.295296 .. versionadded:: 8.2.0297 """298 normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)299300 if ctx is not None and ctx.token_normalize_func is not None:301 normed_value = ctx.token_normalize_func(normed_value)302303 if not self.case_sensitive:304 normed_value = normed_value.casefold()305306 return normed_value307261 def get_metavar(self, param: Parameter) -> str:308 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:309 if param.param_type_name == "option" and not param.show_choices: # type: ignore310 choice_metavars = [311 convert_type(type(choice)).name.upper() for choice in self.choices312 ]313 choices_str = "|".join([*dict.fromkeys(choice_metavars)])314 else:268 choices_str = "|".join([str(i) for i in self.choices])315 choices_str = "|".join(316 [str(i) for i in self._normalized_mapping(ctx=ctx).values()]317 )318319 # Use curly braces to indicate a required argument.320 if param.required and param.param_type_name == "argument":321 return f"{{{choices_str}}}"322323 # Use square braces to indicate an option or optional argument.324 return f"[{choices_str}]"325277 def get_missing_message(self, param: Parameter) -> str:278 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))326 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:327 """328 Message shown when no choice is passed.329330 .. versionchanged:: 8.2.0 Added ``ctx`` argument.331 """332 return _("Choose from:\n\t{choices}").format(333 choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values())334 )335336 def convert(337 self, value: t.Any, param: Parameter | None, ctx: Context | None282 ) -> t.Any:283 # Match through normalization and case sensitivity284 # first do token_normalize_func, then lowercase285 # preserve original `value` to produce an accurate message in286 # `self.fail`287 normed_value = value288 normed_choices = {choice: choice for choice in self.choices}338 ) -> ParamTypeValue:339 """340 For a given value from the parser, normalize it and find its341 matching normalized value in the list of choices. Then return the342 matched "original" choice.343 """344 normed_value = self.normalize_choice(choice=value, ctx=ctx)345 normalized_mapping = self._normalized_mapping(ctx=ctx)346290 if ctx is not None and ctx.token_normalize_func is not None:291 normed_value = ctx.token_normalize_func(value)292 normed_choices = {293 ctx.token_normalize_func(normed_choice): original294 for normed_choice, original in normed_choices.items()295 }347 try:348 return next(349 original350 for original, normalized in normalized_mapping.items()351 if normalized == normed_value352 )353 except StopIteration:354 self.fail(355 self.get_invalid_choice_message(value=value, ctx=ctx),356 param=param,357 ctx=ctx,358 )359297 if not self.case_sensitive:298 normed_value = normed_value.casefold()299 normed_choices = {300 normed_choice.casefold(): original301 for normed_choice, original in normed_choices.items()302 }303304 if normed_value in normed_choices:305 return normed_choices[normed_value]306307 self.fail(self.get_invalid_choice_message(value), param, ctx)308309 def get_invalid_choice_message(self, value: t.Any) -> str:360 def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:361 """Get the error message when the given choice is invalid.362363 :param value: The invalid value.364365 .. versionadded:: 8.2366 """316 choices_str = ", ".join(map(repr, self.choices))367 choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))368 return ngettext(369 "{value!r} is not {choice}.",370 "{value!r} is not one of {choices}.",371 len(self.choices),
60 unmodified lines
432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435385 def get_metavar(self, param: Parameter) -> str:436 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:437 return f"[{'|'.join(self.formats)}]"438439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:440 try:
720 unmodified lines
modified:tests/test_basic.py+79 added
1from __future__ import annotations23import enum4import os5from itertools import chain67import pytest
397 unmodified lines
405 result = runner.invoke(cli, ["--help"])406 assert "{foo|bar|baz}" in result.output407408409def test_choice_argument_enum(runner):410 class MyEnum(str, enum.Enum):411 FOO = "foo-value"412 BAR = "bar-value"413 BAZ = "baz-value"414415 @click.command()416 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))417 def cli(method: MyEnum):418 assert isinstance(method, MyEnum)419 click.echo(method)420421 result = runner.invoke(cli, ["foo"])422 assert result.output == "foo-value\n"423 assert not result.exception424425 result = runner.invoke(cli, ["meh"])426 assert result.exit_code == 2427 assert (428 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"429 " 'bar', 'baz'." in result.output430 )431432 result = runner.invoke(cli, ["--help"])433 assert "{foo|bar|baz}" in result.output434435436def test_choice_argument_custom_type(runner):437 class MyClass:438 def __init__(self, value: str) -> None:439 self.value = value440441 def __str__(self) -> str:442 return self.value443444 @click.command()445 @click.argument(446 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])447 )448 def cli(method: MyClass):449 assert isinstance(method, MyClass)450 click.echo(method)451452 result = runner.invoke(cli, ["foo"])453 assert not result.exception454 assert result.output == "foo\n"455456 result = runner.invoke(cli, ["meh"])457 assert result.exit_code == 2458 assert (459 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"460 " 'bar', 'baz'." in result.output461 )462463 result = runner.invoke(cli, ["--help"])464 assert "{foo|bar|baz}" in result.output465466467def test_choice_argument_none(runner):468 @click.command()469 @click.argument(470 "method", type=click.Choice(["not-none", None], case_sensitive=False)471 )472 def cli(method: str | None):473 assert isinstance(method, str) or method is None474 click.echo(method)475476 result = runner.invoke(cli, ["not-none"])477 assert not result.exception478 assert result.output == "not-none\n"479480 # None is not yet supported.481 result = runner.invoke(cli, ["none"])482 assert result.exception483484485def test_datetime_option_default(runner):486 @click.command()487 @click.option("--start_date", type=click.DateTime())488 def cli(start_date):
166 unmodified lines
modified:tests/test_formatting.py+1 added-1 removed
246 unmodified lines
247248249def test_formatting_custom_type_metavar(runner):250 class MyType(click.ParamType):251 def get_metavar(self, param):251 def get_metavar(self, param: click.Parameter, ctx: click.Context):252 return "MY_TYPE"253254 @click.command("foo")255 @click.help_option()
113 unmodified lines
modified:tests/test_info_dict.py+2 added-2 removed
104 unmodified lines
105 id="UNPROCESSED ParamType",106 ),107 pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"),108 pytest.param(109 click.Choice(["a", "b"]),109 click.Choice(("a", "b")),110 {111 "param_type": "Choice",112 "name": "choice",113 "choices": ["a", "b"],113 "choices": ("a", "b"),114 "case_sensitive": True,115 },116 id="Choice ParamType",117 ),
158 unmodified lines
modified:tests/test_normalization.py+30 added-5 removed
15 unmodified lines
161718def test_choice_normalization(runner):19 @click.command(context_settings=CONTEXT_SETTINGS)20 @click.option("--choice", type=click.Choice(["Foo", "Bar"]))21 def cli(choice):22 click.echo(choice)20 @click.option(21 "--method",22 type=click.Choice(23 ["SCREAMING_SNAKE_CASE", "snake_case", "PascalCase", "kebab-case"],24 case_sensitive=False,25 ),26 )27 def cli(method):28 click.echo(method)2924 result = runner.invoke(cli, ["--CHOICE", "FOO"])25 assert result.output == "Foo\n"30 result = runner.invoke(cli, ["--METHOD=snake_case"])31 assert not result.exception, result.output32 assert result.output == "snake_case\n"3334 # Even though it's case sensitive, the choice's original value is preserved35 result = runner.invoke(cli, ["--method=pascalcase"])36 assert not result.exception, result.output37 assert result.output == "PascalCase\n"3839 result = runner.invoke(cli, ["--method=meh"])40 assert result.exit_code == 241 assert (42 "Invalid value for '--method': 'meh' is not one of "43 "'screaming_snake_case', 'snake_case', 'pascalcase', 'kebab-case'."44 ) in result.output4546 result = runner.invoke(cli, ["--help"])47 assert (48 "--method [screaming_snake_case|snake_case|pascalcase|kebab-case]"49 in result.output50 )515253def test_command_normalization(runner):54 @click.group(context_settings=CONTEXT_SETTINGS)55 def cli():56 pass
7 unmodified lines
modified:tests/test_types.py+1 added-1 removed
246 unmodified lines
247248249def test_choice_get_invalid_choice_message():250 choice = click.Choice(["a", "b", "c"])251 message = choice.get_invalid_choice_message("d")251 message = choice.get_invalid_choice_message("d", ctx=None)252 assert message == "'d' is not one of 'a', 'b', 'c'."
modified:CHANGES.rst+5 added-2 removed
86 unmodified lines
87 ``(Deprecated) help`` to ``help (DEPRECATED)``.88 - Parameters cannot be required nor prompted or an error is raised.89 - A warning will be printed when something deprecated is used.9091- Add a ``catch_exceptions`` parameter to :class:`CliRunner`. If92 ``catch_exceptions`` is not passed to :meth:`CliRunner.invoke`,91- Add a ``catch_exceptions`` parameter to :class:``CliRunner``. If92 ``catch_exceptions`` is not passed to :meth:``CliRunner.invoke``,93 the value from :class:`CliRunner`. :issue:`2817` :pr:`2818`94- ``Option.flag_value`` will no longer have a default value set based on95 ``Option.default`` if ``Option.is_flag`` is ``False``. This results in96 ``Option.default`` not needing to implement `__bool__`. :pr:`2829`97- Incorrect ``click.edit`` typing has been corrected. :pr:`2804`98- :class:``Choice`` is now generic and supports any iterable value.99 This allows you to use enums and other non-``str`` values. :pr:`2796`100 :issue:`605`101102Version 8.1.8103-------------104
1117 unmodified lines