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
Provenance
- Commit
4ece17a- Tree
33ec91e- Author
Andreas Backx <AndreasBackx@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
8a47580
10 files changed+238 added−70 removed
modified:docs/options.rst+14 added-6 removed
373 unmodified lines374 In that case you can use :class:`Choice` type. It can be instantiated375 with a list of valid values. The originally passed choice will be returned,376 not 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.379 380 Example:381 382 .. click:example::383 384+ import enum385+386+ class HashType(enum.Enum):387+ MD5 = 'MD5'388+ SHA1 = 'SHA1'389+390 @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)395 396 What it looks like:397 6 unmodified lines404 invoke(digest, args=['--hash-type=foo'])405 println()406 invoke(digest, args=['--help'])407 401-Only pass the choices as list or tuple. Other iterables (like402-generators) may lead to unexpected results.408+Since version 8.2.0 any iterable may be passed to :class:`Choice`, here409+an ``Enum`` is used which will result in all enum values to be valid410+choices.411 412 Choices work with options that have ``multiple=True``. If a ``default``413 value is given with ``multiple=True``, it should be a list or tuple of414 valid choices.415 408-Choices should be unique after considering the effects of409-``case_sensitive`` and any specified token normalization function.416+Choices should be unique after normalization, see417+:meth:`Choice.normalize_choice` for more info.418 419 .. versionchanged:: 7.1420 The resulting value from an option will always be one of the421 originally passed choices regardless of ``case_sensitive``.514 unmodified linesmodified:src/click/core.py+7 added-7 removed
2190 unmodified lines2191 same as the name for options, but the metavar for arguments.2192 """2193 return self.name # type: ignore2194 2195- def make_metavar(self) -> str:2195+ def make_metavar(self, ctx: Context) -> str:2196 if self.metavar is not None:2197 return self.metavar2198 2199- metavar = self.type.get_metavar(self)2199+ metavar = self.type.get_metavar(param=self, ctx=ctx)2200 2201 if metavar is None:2202 metavar = self.type.name.upper()2203 570 unmodified lines2774 if any_slashes:2775 any_prefix_is_slash = True2776 2777 if not self.is_flag and not self.count:2778- rv += f" {self.make_metavar()}"2778+ rv += f" {self.make_metavar(ctx=ctx)}"2779 2780 return rv2781 2782 rv = [_write_opts(self.opts)]272 unmodified lines3055 if self.metavar is not None:3056 return self.metavar3057 return self.name.upper() # type: ignore3058 3059- 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 lines3087 )3088 return name, [arg], []3089 3090 def get_usage_pieces(self, ctx: Context) -> list[str]:3091- return [self.make_metavar()]3091+ return [self.make_metavar(ctx)]3092 3093 def get_error_hint(self, ctx: Context) -> str:3094- return f"'{self.make_metavar()}'"3094+ return f"'{self.make_metavar(ctx)}'"3095 3096 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 linesmodified:src/click/exceptions.py+3 added-1 removed
172 unmodified lines173 param_type = self.param.param_type_name174 175 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 linesmodified:src/click/types.py+96 added-45 removed
1 from __future__ import annotations2 3 import collections.abc as cabc4+import enum5 import os6 import stat7 import sys8 import typing as t14 unmodified lines23 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem26 27+ParamTypeValue = t.TypeVar("ParamTypeValue")28 29+30 class 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 lines88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)91 89- 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."""94 92- 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.98 99 .. versionadded:: 2.0129 unmodified lines229 def __repr__(self) -> str:230 return "STRING"231 232 230-class Choice(ParamType):233+class 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.236 234- 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.239 237- 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.243 241- See :ref:`choice-opts` for an example.242-244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.246+247+ .. 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.251+252+ .. versionadded:: 8.2.0253+ Choice normalization can be overridden via :meth:`normalize_choice`.254 """255 256 name = "choice"257 258 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_sensitive263 264 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_dict269 270+ 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.276+277+ 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+ }287+288+ 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.292+293+ By default uses :meth:`Context.token_normalize_func` and if not case294+ sensitive, convert it to a casefolded value.295+296+ .. versionadded:: 8.2.0297+ """298+ normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)299+300+ if ctx is not None and ctx.token_normalize_func is not None:301+ normed_value = ctx.token_normalize_func(normed_value)302+303+ if not self.case_sensitive:304+ normed_value = normed_value.casefold()305+306+ return normed_value307+261- 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+ )318 319 # Use curly braces to indicate a required argument.320 if param.required and param.param_type_name == "argument":321 return f"{{{choices_str}}}"322 323 # Use square braces to indicate an option or optional argument.324 return f"[{choices_str}]"325 277- 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.329 330+ .. 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+ )335+336 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)346 290- 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+ )359 297- 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- }303-304- if normed_value in normed_choices:305- return normed_choices[normed_value]306-307- self.fail(self.get_invalid_choice_message(value), param, ctx)308-309- 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.362 363 :param value: The invalid value.364 365 .. 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 lines432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435 385- def get_metavar(self, param: Parameter) -> str:436+ def get_metavar(self, param: Parameter, ctx: Context) -> str | None:437 return f"[{'|'.join(self.formats)}]"438 439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:440 try:720 unmodified linesmodified:tests/test_basic.py+79 added
1+from __future__ import annotations2+3+import enum4 import os5 from itertools import chain6 7 import pytest397 unmodified lines405 result = runner.invoke(cli, ["--help"])406 assert "{foo|bar|baz}" in result.output407 408 409+def test_choice_argument_enum(runner):410+ class MyEnum(str, enum.Enum):411+ FOO = "foo-value"412+ BAR = "bar-value"413+ BAZ = "baz-value"414+415+ @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)420+421+ result = runner.invoke(cli, ["foo"])422+ assert result.output == "foo-value\n"423+ assert not result.exception424+425+ 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+ )431+432+ result = runner.invoke(cli, ["--help"])433+ assert "{foo|bar|baz}" in result.output434+435+436+def test_choice_argument_custom_type(runner):437+ class MyClass:438+ def __init__(self, value: str) -> None:439+ self.value = value440+441+ def __str__(self) -> str:442+ return self.value443+444+ @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)451+452+ result = runner.invoke(cli, ["foo"])453+ assert not result.exception454+ assert result.output == "foo\n"455+456+ 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+ )462+463+ result = runner.invoke(cli, ["--help"])464+ assert "{foo|bar|baz}" in result.output465+466+467+def 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)475+476+ result = runner.invoke(cli, ["not-none"])477+ assert not result.exception478+ assert result.output == "not-none\n"479+480+ # None is not yet supported.481+ result = runner.invoke(cli, ["none"])482+ assert result.exception483+484+485 def test_datetime_option_default(runner):486 @click.command()487 @click.option("--start_date", type=click.DateTime())488 def cli(start_date):166 unmodified linesmodified:tests/test_formatting.py+1 added-1 removed
246 unmodified lines247 248 249 def 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"253 254 @click.command("foo")255 @click.help_option()113 unmodified linesmodified:tests/test_info_dict.py+2 added-2 removed
104 unmodified lines105 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 linesmodified:tests/test_normalization.py+30 added-5 removed
15 unmodified lines16 17 18 def 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)29 24- 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"33 34+ # 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"38 39+ 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.output45+46+ result = runner.invoke(cli, ["--help"])47+ assert (48+ "--method [screaming_snake_case|snake_case|pascalcase|kebab-case]"49+ in result.output50+ )51+52+53 def test_command_normalization(runner):54 @click.group(context_settings=CONTEXT_SETTINGS)55 def cli():56 pass7 unmodified linesmodified:tests/test_types.py+1 added-1 removed
246 unmodified lines247 248 249 def 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 lines87 ``(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.90 91-- 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`101 102 Version 8.1.8103 -------------104 1117 unmodified lines