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
I can work around it as described here it would be great if Choice supported Python Enum.
Unless of course I have missed something completely fundamental :-)
Reacted by Aleksandr Baryshnikov, David Gidwani, ksonj, Stefan Scherfke, Sebastian Yonekura, Andrii Oriekhov, Dan Søndergaard, Flip van Rijn, Yevhenii Kovalchuk, Omer Katz and 52 more
from . importconst@dispatch.command()@click.option('--output', '-o', type=click.Choice(const.ConfigFormat),help='Sets default output format for configuration files')@pass_projectdefinit(project, output, force):
"""Initialises a managed schema"""click.echo(project.schema_home)
Reacted by David Fallah, Xevion, Giorgio Balestrieri, Edgar Ramírez Mondragón, Brandon Stilson, Micael Jarniac, Javier Maestro, Martijn Pieters, Ivan Ms, Ilya Siamionau and 7 more
$ python click_enum.py
Usage: click_enum.py [OPTIONS] [a|b|c]
Try 'click_enum.py --help' for help.
Error: Missing argument '[a|b|c]'. Choose from:
a,
b,
c.
$ python click_enum.py a
MyEnum.A
<enum 'MyEnum'>
$ python click_enum.py d
Usage: click_enum.py [OPTIONS] [a|b|c]
Try 'click_enum.py --help' for help.
Error: Invalid value for '[a|b|c]': invalid choice: d. (choose from a, b, c)
Reacted by Maximilian Roos, Ahmed Shariff, Émile Fugulin, Andrii Oriekhov, m0wer, Maksim Kalmykov, Jan Katins, Enzo Caceres, Brent Vollebregt and André Roggeri Campos
Reacted by Allan Lewis, Anders Bennedsgaard, Émile Fugulin, ben1mit, Andrii Oriekhov, Lee Netherton, Ondřej Vacek, Jan Katins, Goto Hayato, Ganesh Kathiresan and 1 more
$ cat click_test.py
import click
import enum
class MyEnum(str, enum.Enum):
A = "a"
B = "b"
C = "c"
@click.command("my-cmd")
@click.argument("which_option", type=click.Choice(MyEnum))
def my_cmd(which_option: MyEnum):
print(which_option)
print(type(which_option))
if __name__ == "__main__":
my_cmd()
Still Gives:
click_test.py:12: error: Argument 1 to "Choice" has incompatible type "Type[MyEnum]"; expected "Sequence[str]"
Found 1 error in 1 file (checked 1 source file)
Let's try and finally get this in 8.2.0. If anyone has any feedback, I've put up #2796. Looking for feedback as I'm going to continue to look through the other open issues / PRs that are on the list to be included in 8.2.0, see the 8.2.0 Release Plan. It might be a better and it might be worse than #2210, let me know which one it is!
Reacted by bigeagle
Reacted by Raphael, SpoopyTim, Chris Withers, daxida and Ahmed Shariff
Activity
mitsuhiko commentedon Jul 9, 2016
What exactly is implied with supporting an enum?
devraj commentedon Jul 9, 2016
To be able to use
Enuminstead oftuplesforChoicevalues, i.e define it as suchand then use it in the decorator as follows
aldanor commentedon Jul 25, 2016
enumis only available in Python 3 though (in Python 2 you have to use an external backport).TAGC commentedon Sep 8, 2016
untitaker commentedon Sep 8, 2016
TAGC commentedon Sep 8, 2016
I was being facetious, sorry. It would be a neat feature but it's nothing essential by any means. Loving this tool by the way.
allanlewis commentedon Dec 6, 2016
I'm using something like this in my code, where I'm using Python 2.7 with
enum34==1.1.6:The callback provides
enum_valas the actual enumeration instance rather than a string, orNoneif the option wasn't given.Perhaps this could be wrapped into another decorator, like
click.enum_option:@click.enum_option('--enum-val', enum=MyEnum)UPDATE: In review, others thought that callback was rather ugly, which it is, so I've removed it. If it was inside
click, it might be OK.skycaptain commentedon Feb 5, 2017
The easiest way I can think of, is to use a custom type (Although I think this would be a nice feature for click):
You might overwrite
get_metavarto compute the metavar from class name (since the complete choice list might be to long for a cli printout):... def get_metavar(self, param): # Gets metavar automatically from enum name word = self.__enum.__name__ # Stolen from jpvanhal/inflection word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word) word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word) word = word.replace("-", "_").lower().split("_") if word[-1] == "enum": word.pop() return ("_".join(word)).upper() ...Since Enums are sometimes written uppercase, feel free to write a case insensitive version of the above code. E.g. one could start off with
This way you can either add a complete Enum or you can just use some values as a choice (listed as a tuple).
EnumType type for Click
EnumType type for Click
aomader commentedon Jun 21, 2019
A bit old but I thought I add the nice idea of using
strEnums for options (which is also great for old-schoolstr-based settings w.r.t. comparisons).gazpachoking commentedon Feb 5, 2020
Here's my take on supporting this:
Allows using either the names or values of the enum items based on the
use_valueparameter. Should work whether values are strings or not.bartekpacia commentedon Aug 2, 2020
I don't know if somebody posted it here, but that's how I dealt with it:
5 remaining items
ShivKJ commentedon Sep 10, 2021
@yashrathi-git a minor change in the code you provided,
But I feel this should be done under the hood instead of importing EnumType.
In other words, it would be much more desirable if we could write,
@click.option("-m", "--method", type=Test, default = 'test') # or default = Test.testjerluc commentedon Dec 29, 2021
I know this thread is pretty old, but I've been using this pattern for
str + Enums, which IMO is pretty clean and intuitive:rdbisme commentedon Jan 19, 2022
Hello @jerluc, your pattern works functionally, but it fails type checking
jerluc commentedon Jan 19, 2022
Does it @rdbisme? I don't see any issues using latest mypy (0.931) on Python 3.7:
rdbisme commentedon Jan 21, 2022
Well,
Still Gives:
dzcode commentedon May 2, 2022
I'm at the PyCon sprint now and could work on this
davidism commentedon May 2, 2022
@dzcode thanks, but there's already an open PR for this.
MicaelJarniac commentedon May 3, 2022
#2210?
AndreasBackx commentedon Nov 2, 2024
Let's try and finally get this in 8.2.0. If anyone has any feedback, I've put up #2796. Looking for feedback as I'm going to continue to look through the other open issues / PRs that are on the list to be included in 8.2.0, see the 8.2.0 Release Plan. It might be a better and it might be worse than #2210, let me know which one it is!
racinmat commentedon Nov 20, 2024
Regarding the typecheck of
@click.argument("which_option", type=click.Choice(MyEnum))this is what works for me and the typecheck passes
@click.argument("which_option", type=click.Choice(list(MyEnum)))kdeldycke commentedon Nov 18, 2025
For the record,
click.Choiceis supportingEnums, but naively: theEnum.nameproperty of each members is used for choices. It was designed that way to simplify the implementation, because it is the part ofEnumthat is guaranteed to be unique strings.If you need more flexible source of string values, you can use Click Extra's
EnumChoice.