Last active
March 10, 2021 07:39
-
-
Save linw1995/19d5d9285fc8135b14ff0069d433fa97 to your computer and use it in GitHub Desktop.
Click with optional arguments which are enum type.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Standard Library | |
| import enum | |
| # Third Party Library | |
| import click | |
| class Order(enum.Enum): | |
| latest = "latest" | |
| oldest = "oldest" | |
| class Predicate(enum.Enum): | |
| is_video = "is_video" | |
| is_images = "is_images" | |
| def parse_enum_option(enum_cls): | |
| def callback(ctx, param, value): | |
| return enum_cls[value] | |
| return callback | |
| def ClickEnumType(enum_cls): | |
| return click.Choice([e.name for e in enum_cls]) | |
| @click.command() | |
| @click.option( | |
| "-o", | |
| "--order", | |
| default="latest", # or Order.latest.name | |
| type=ClickEnumType(Order), | |
| callback=parse_enum_option(Order), | |
| ) | |
| @click.option( | |
| "-p", | |
| "--predicate", | |
| default="is_video", # or Predicate.is_video.name | |
| type=ClickEnumType(Predicate), | |
| callback=parse_enum_option(Predicate), | |
| ) | |
| def query(order: Order, predicate: Predicate): | |
| print(order, predicate) | |
| if __name__ == "__main__": | |
| query() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $ python demo.py --help | |
| Usage: demo.py [OPTIONS] | |
| Options: | |
| -o, --order [latest|oldest] | |
| -p, --predicate [is_video|is_images] | |
| --help Show this message and exit. | |
| $ python demo.py | |
| Order.latest Predicate.is_video |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment