swansonk14 / typed-argument-parser

Typed argument parser for Python
MIT License
497 stars 40 forks source link

feature-request: List options for enums in the help-message #70

Open bjuergens opened 2 years ago

bjuergens commented 2 years ago

hello,

Could you make it so that options for enums appear in the help-message?

here is a code example

from enum import Enum
from typing import Literal
from tap import Tap

class MyEnum(str, Enum):
    A = "aaa"
    B = "bbb"
    C = "ccc"

    def __str__(self):
        # it would be nice if this overwrite wouldn't be needed
        return self.value

class MyArgs(Tap):
    myEnum1: MyEnum = MyEnum.A  # here options are not listed
    myEnum2: Literal[MyEnum.A, MyEnum.B, MyEnum.C] = MyEnum.A  # workaround, that repeats all options

    def configure(self):
        # this works fine, but it would be neat if it wasn't needed
        self.add_argument('--myEnum3', type=MyEnum, choices=list(MyEnum))

print(MyArgs().parse_args())

help-message:

 $ python main2.py -h                                       
usage: main2.py [--myEnum1 MYENUM1] [--myEnum2 {aaa,bbb,ccc}] [-h] --myEnum3 {aaa,bbb,ccc}

optional arguments:
  --myEnum1 MYENUM1     (<enum 'MyEnum'>, default=aaa) here options are not listed
  --myEnum2 {aaa,bbb,ccc}
                        (Literal[<MyEnum.A: 'aaa'>, <MyEnum.B: 'bbb'>, <MyEnum.C: 'ccc'>], default=aaa) workaround, that repeats all options
  -h, --help            show this help message and exit
  --myEnum3 {aaa,bbb,ccc}
                        (required)

the actual parsed values are as expected the same in all 3 cases:

$ python main2.py --myEnum1 aaa --myEnum2 bbb --myEnum3 ccc                                                                                                                                                                                         
{'myEnum1': <MyEnum.A: 'aaa'>,
 'myEnum2': <MyEnum.B: 'bbb'>,
 'myEnum3': <MyEnum.C: 'ccc'>}

Additional note: i have considered literals, but they are weird when used together with enums. I want enums because later if use the old "if elif elif" to handle the selected option, When I use string-literals there, typos will become an issue. Also with enums I can "jump to source" in my IDE. It would be neat if I could convert an enum to a literal (or vice verse) without repeating all options, but I have not found a way to do this.

swansonk14 commented 2 years ago

Hi @bjuergens,

Thank you for the great issue! This is a wonderful idea and we plan to implement it soon!

Best, Jesse and Kyle