`StrEnum` with `type=click.Choice(...)` incorrect output on unknown value
Environment:
- Python version: ^3.12
- Click version: ^8.1.7
class MyEnum(enum.StrEnum):
SMTH = enum.auto()
AMTH = enum.auto()
# --snip --
@click.option(
"--output-format",
type=click.Choice(list(MyEnum))
)
# using `list` to avoid mypy erorr: Argument 1 to "Choice" has incompatible type "type[MyEnum]"; expected "Sequence[str]"
Expected output on an unknown choice:
Error: Invalid value for '--output-format': 'i_do_not_exist' is not one of 'smth', 'amth'.
Actual output:
Error: Invalid value for '--output-format': 'i_do_not_exist' is not one of <MyEnum.SMTH: 'smth'>, <MyEnum.AMTH: 'amth'>.
~The issue seems to originate from the fact that click uses repr(MyEnum.SMTH) instead of str(MyEnum.SMTH).~
~I am able to fix the issue by adding this piece of code to my enum class, but it is a hack and should not be advised as a proper solution.~
def __repr__(self) -> str:
return str(self)
UPD: The proper and non-hacky fix is to do this. This way you don't need to change __repr__ implementation.
@click.option(
"--output-format",
type=click.Choice(list(map(str, MyEnum))),
)
This (1) should be stated in the documentation (right now there is no information about enums at all, actually), and (2) stated in this https://github.com/pallets/click/issues/605 thread. That's where I found you can use Enums as choices. And latest comment suggests using type=click.Choice(list(MyEnum)) instead of type=click.Choice(list(map(str, MyEnum))) which is incorrect.
Preferably, click should do this conversion automatically. In my opinion, you should only need to do this type=click.Choice(MyEnum).
Duplicate of #605, targeted for 8.2.