Skip to content

Commit

Permalink
feat: new method for choice fail (#2622)
Browse files Browse the repository at this point in the history
Co-authored-by: Andreas Backx <[email protected]>
  • Loading branch information
antazoey and AndreasBackx authored Nov 3, 2024
1 parent 1787497 commit 4271fe2
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 9 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ Unreleased
- When using ``Option.envvar`` with ``Option.flag_value``, the ``flag_value``
will always be used instead of the value of the environment variable.
:issue:`2746` :pr:`2788`
- Add ``Choice.get_invalid_choice_message`` method for customizing the
invalid choice message. :issue:`2621` :pr:`2622`


Version 8.1.8
Expand Down
1 change: 1 addition & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Types
.. autoclass:: Path

.. autoclass:: Choice
:members:

.. autoclass:: IntRange

Expand Down
23 changes: 14 additions & 9 deletions src/click/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,16 +304,21 @@ def convert(
if normed_value in normed_choices:
return normed_choices[normed_value]

self.fail(self.get_invalid_choice_message(value), param, ctx)

def get_invalid_choice_message(self, value: t.Any) -> str:
"""Get the error message when the given choice is invalid.
:param value: The invalid value.
.. versionadded:: 8.2
"""
choices_str = ", ".join(map(repr, self.choices))
self.fail(
ngettext(
"{value!r} is not {choice}.",
"{value!r} is not one of {choices}.",
len(self.choices),
).format(value=value, choice=choices_str, choices=choices_str),
param,
ctx,
)
return ngettext(
"{value!r} is not {choice}.",
"{value!r} is not one of {choices}.",
len(self.choices),
).format(value=value, choice=choices_str, choices=choices_str)

def __repr__(self) -> str:
return f"Choice({list(self.choices)})"
Expand Down
6 changes: 6 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,9 @@ def test_invalid_path_with_esc_sequence():
click.Path(dir_okay=False).convert(tempdir, None, None)

assert "my\\ndir" in exc_info.value.message


def test_choice_get_invalid_choice_message():
choice = click.Choice(["a", "b", "c"])
message = choice.get_invalid_choice_message("d")
assert message == "'d' is not one of 'a', 'b', 'c'."

0 comments on commit 4271fe2

Please sign in to comment.