click icon indicating copy to clipboard operation
click copied to clipboard

`StrEnum` with `type=click.Choice(...)` incorrect output on unknown value

Open nikableh opened this issue 1 year ago • 3 comments

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'>.

nikableh avatar Mar 08 '25 11:03 nikableh

~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)

nikableh avatar Mar 08 '25 11:03 nikableh

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).

nikableh avatar Mar 08 '25 12:03 nikableh

Duplicate of #605, targeted for 8.2.

davidism avatar Mar 08 '25 13:03 davidism