-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support enum param type #10
base: master
Are you sure you want to change the base?
Conversation
@@ -139,3 +140,33 @@ def convert(self, value, param, ctx): | |||
|
|||
def __repr__(self): | |||
return self.name.upper() | |||
|
|||
|
|||
class EnumParamType(CustomParamType): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we probably want to implement __repr__
, get_missing_message
and shell_complete
methods from the click.Choice
class
Hi @saroad2 , thanks for the proposal.
I was a bit skeptical about this and it works for me unless I don't understand the issue. I'm using click 8.X.X import enum
import click
class Hash(enum.Enum):
MD5 = 'MD5'
SHA1 = 'SHA1'
def convert_to_enum(ctx, param, value):
if value:
return Hash[value]
@click.command()
@click.option(
'--hash-type',
type=click.Choice(['MD5', 'SHA1'], case_sensitive=False),
callback=convert_to_enum
)
def cli(hash_type):
"""Test cli"""
click.echo(hash_type) Nevertheless, we can still add a native enum type :) |
Oh, that's super weird. For some reason it didn't work for me. I guess I just did something wrong. If that's so, there are two ways to move forward:
Both options are valid in my opinion. |
I think the second approach is better i.e reusing But ultimetaly, you can directly propose your change on the click project :-) |
I will give it a try. The people maintaining Click seem to reject most of my ideas. |
Ack, if you can give me the link to your PR on the click project, I will appreciate :) So I can also follow the progress. |
Hey, no problem. |
Thanks |
Description
Added a new ability to be able to create a choice parameter type from enum class.
Why not using
click.Choice
?click.Choice
always returns a string and can't be modified to into any other type. if you try to do that using thecallback
parameter, it will fail.On the other hand, enums are the way of python to allow only a finite number of values to be accepted in a given scenario. It seems to me like to logical step that
click.Choice
should have returned an enum.Now, using
EnumParamType
, one can create a choice-like parameter that returns an enum instead of a string.Moreover, once you add a new value to your enum class, it will automatically update as a valid choice for the paramater type.