Created
March 30, 2025 20:28
-
-
Save yuri1969/22c1e403fe3ad95240bc61eed38a36a3 to your computer and use it in GitHub Desktop.
enum argparse
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
#!/usr/bin/env python3 | |
'''Enum argparse''' | |
import argparse | |
import enum | |
from dataclasses import dataclass | |
@dataclass | |
class ColorDef: | |
'''Color definition''' | |
label: str | |
hex_value: str | |
class Color(enum.Enum): | |
'''Available colors''' | |
RED = ColorDef('red', '#FF0000') | |
GREEN = ColorDef('green', '#00FF00') | |
BLUE = ColorDef('blue', '#0000FF') | |
def __str__(self) -> str: | |
return self.name # Ensures argparse displays values as strings | |
def parse_enum(enum_type: type[Color]) -> Color: | |
'''Argparse type function to parse enum values.''' | |
def parser(value: str) -> Color: | |
for item in enum_type: | |
if value == item.name: | |
return item | |
raise argparse.ArgumentTypeError( | |
f"Invalid choice: '{value}'. Choose from {[e.name for e in enum_type]}" | |
) | |
return parser | |
def main() -> None: | |
'''Entry point''' | |
parser = argparse.ArgumentParser(description='Example with Enum arguments.') | |
parser.add_argument( | |
'-c', '--color', | |
type=parse_enum(Color), | |
default=Color.RED, | |
choices=list(Color), # Enables argparse's help message support | |
required=False, | |
help='Choose a color. (Default RED)' | |
) | |
args = parser.parse_args() | |
print(f'Selected color: {args.color}, Hex: {args.color.value.hex_value}') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment