You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Choice prefers Enum.name even for StrEnum where it should use the value #2911
With Click 8.1.8, running this script with -C red works as expected, but with Click 8.2.0, it instead fails with:
Usage: enum-choice01a.py [OPTIONS]
Try 'enum-choice01a.py --help' for help.
Error: Invalid value for '-C' / '--color': 'red' is not one of 'RED', 'GREEN', 'BLUE'.
This was observed with Python 3.13.3 on macOS 14.7.5.
Reacted by qdegraaf, Michael J. Sullivan and David Linke
And if so, is this behaviour intentional? If not, I'd be happy to open a PR with an additional test for Enum's that are also str's and tweak the line to return the string value in that additional case. I am new to the repo though so could be missing context.
changed the title [-]`Choice` in Click 8.2.0 stringifies enums by `name`, even when they're `str` subclasses[/-][+]`Choice` stringifies enums by `name`, even when they're `str` subclasses[/+]on May 13, 2025
I've replicated the example as a test and see now that it is think it might be by design. case_sensitive: bool = True by default. @jwodder setting case_sensitive to False in click.Choice makes your example above work for me.
I guess the follow-up question is whether this default is desirable. I could see quite a few
that are currently being used in click.Choice that all implicitly used the str values of the Enum values.
We experienced a similar, but not exactly the same, issue for StrEnum default values in the typer.Option wrapper around click.Choice where something like:
What about enums where the value isn't just the lowercase version of the name? (e.g., MULTI_VALUE = "multi-value") case_sensitive won't help with those, and normalize_choice() is only available in Click 8.2.0.
Just guessing based on the default value and the way the function is written. Apologies, I should not have stated it so definitively. I am not a developer on click so it's a question for the maintainers or the developer of the feature. Maybe @AndreasBackx can shed some light?
@qdegraaf#2796 added support for Enum in general, StrEnum (or well class StrEnum(str, Enum)) is slightly different. Enum.name is used in the implementation because Enum can be anything. Then token normalisation is applied. Let me rename the issue to reflect this.
A good solution would perhaps be to get the starting value in Choice.normalize_choice to be like the following:
def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:
"""
Normalize a choice value, used to map a passed string to a choice.
Each choice must have a unique normalized value.
By default uses :meth:`Context.token_normalize_func` and if not case
sensitive, convert it to a casefolded value.
.. versionadded:: 8.2.0
"""
- normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)+ match choice:+ case str(choice):+ normed_value = choice+ case Enum(choice):+ normed_value = choice.name+ case _:+ normed_value = str(choice)
if ctx is not None and ctx.token_normalize_func is not None:
normed_value = ctx.token_normalize_func(normed_value)
if not self.case_sensitive:
normed_value = normed_value.casefold()
return normed_value
changed the title [-]`Choice` stringifies enums by `name`, even when they're `str` subclasses[/-][+]`Choice` prefers `Enum.name` even for `StrEnum` where it should use the value[/+]on May 14, 2025
Thanks for clarifying! Because the tests used a class MyEnum(str, enum.Enum), I thought maybe it was supposed to work out of the box for that specific scenario as well.
In the case of a class that is both str and Enum do we want to allow both .name and str()? The solution direction provided above will make the current test_choice_argument_enum fail at the following assert.
assert"Usage: cli [OPTIONS] {foo-value|bar-value|baz-value}\nTry 'cli --help' for help.\n\nError: Invalid value for '{foo-value|bar-value|baz-value}': 'foo' is not one of 'foo-value', 'bar-value', 'baz-value'.\n"=='foo-value\n'
Which makes sense of course, but could undermine the original intention.
I don't like the idea of using value for string enums but name for others. That's inconsistent and will result in further bug reports down the road. name is the part of an enum that will always be a string, that's what we can use.
In the mean time, if you need a more flexible Choice type, I just implemented an EnumChoice type in Click Extra. By default, it uses the __str__ method of your Enum to source the string values to use for choices.
But you can configure it to source the value strings from the name or value. Or a callable.
As a bonus, if you use Click Extra own @command or @group, the default value will reflect your choices.
Activity
qdegraaf commentedon May 13, 2025
Could this be the culprit: https://github.com/pallets/click/pull/2796/files#diff-dcb534e6a7591b92836537d4655ddbd2f18e3b293c3420144c30a9ca08f65c4eR298 ?
And if so, is this behaviour intentional? If not, I'd be happy to open a PR with an additional test for
Enum's that are alsostr's and tweak the line to return the string value in that additional case. I am new to the repo though so could be missing context.[-]`Choice` in Click 8.2.0 stringifies enums by `name`, even when they're `str` subclasses[/-][+]`Choice` stringifies enums by `name`, even when they're `str` subclasses[/+]qdegraaf commentedon May 13, 2025
I've replicated the example as a test and
see now that it isthink it might be by design.case_sensitive: bool = Trueby default. @jwodder settingcase_sensitivetoFalseinclick.Choicemakes your example above work for me.I guess the follow-up question is whether this default is desirable. I could see quite a few
that are currently being used in
click.Choicethat all implicitly used thestrvalues of theEnumvalues.We experienced a similar, but not exactly the same, issue for
StrEnumdefault values in thetyper.Optionwrapper aroundclick.Choicewhere something like:broke as
SomeStrEnum.FOOwas now not one of"foo"|"bar". I could see case insensitive defaults occurring in similar scenarios there.EDIT: Looping in @tiangolo in case reports of scenarios above come in for Typer as well and the click connection isn't immediately clear
jwodder commentedon May 13, 2025
@qdegraaf
valueisn't just the lowercase version of thename? (e.g.,MULTI_VALUE = "multi-value")case_sensitivewon't help with those, andnormalize_choice()is only available in Click 8.2.0.qdegraaf commentedon May 13, 2025
Just guessing based on the default value and the way the function is written. Apologies, I should not have stated it so definitively. I am not a developer on
clickso it's a question for the maintainers or the developer of the feature. Maybe @AndreasBackx can shed some light?BF(workaround): disallow click 8.2.0 due to regression
AndreasBackx commentedon May 14, 2025
@qdegraaf #2796 added support for
Enumin general,StrEnum(or wellclass StrEnum(str, Enum)) is slightly different.Enum.nameis used in the implementation becauseEnumcan be anything. Then token normalisation is applied. Let me rename the issue to reflect this.A good solution would perhaps be to get the starting value in
Choice.normalize_choiceto be like the following:def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str: """ Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value. By default uses :meth:`Context.token_normalize_func` and if not case sensitive, convert it to a casefolded value. .. versionadded:: 8.2.0 """ - normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) + match choice: + case str(choice): + normed_value = choice + case Enum(choice): + normed_value = choice.name + case _: + normed_value = str(choice) if ctx is not None and ctx.token_normalize_func is not None: normed_value = ctx.token_normalize_func(normed_value) if not self.case_sensitive: normed_value = normed_value.casefold() return normed_value[-]`Choice` stringifies enums by `name`, even when they're `str` subclasses[/-][+]`Choice` prefers `Enum.name` even for `StrEnum` where it should use the value[/+]qdegraaf commentedon May 15, 2025
Thanks for clarifying! Because the tests used a
class MyEnum(str, enum.Enum), I thought maybe it was supposed to work out of the box for that specific scenario as well.In the case of a class that is both
strandEnumdo we want to allow both.nameandstr()? The solution direction provided above will make the currenttest_choice_argument_enumfail at the following assert.Which makes sense of course, but could undermine the original intention.
kieranyyu commentedon May 19, 2025
Working on this (PyCon 2025)
davidism commentedon May 19, 2025
I don't like the idea of using
valuefor string enums butnamefor others. That's inconsistent and will result in further bug reports down the road.nameis the part of an enum that will always be a string, that's what we can use.jwodder commentedon May 19, 2025
@davidism What about just using
str(choice)whereisinstance(choice, str)? That gives you the same result forStrEnums and otherstr-likes.davidism commentedon May 19, 2025
That will still result in unexpected inconsistencies in enums. I'm marking this as a documentation fix rather than something we'll change.
If custom behavior is needed, then a custom type or callback can be written to do exactly what that application needs.
kdeldycke commentedon Nov 18, 2025
In the mean time, if you need a more flexible
Choicetype, I just implemented anEnumChoicetype in Click Extra. By default, it uses the__str__method of yourEnumto source the string values to use for choices.But you can configure it to source the value strings from the name or value. Or a callable.
As a bonus, if you use Click Extra own
@commandor@group, the default value will reflect your choices.