abseil / abseil-py

Abseil Common Libraries (Python)
Apache License 2.0
2.29k stars 245 forks source link

DEFINE_enum supports Enum? #207

Closed TRSasasusu closed 1 year ago

TRSasasusu commented 1 year ago

Are there any plans to support Enum in DEFINE_enum?

For example, main.py:

from enum import Enum, auto
from absl import app, flags

class Color(Enum):
    RED = auto()
    GREEN = auto()

flags.DEFINE_enum('color', Color.RED, Color, 'set color', use_lower_case=True) # supporting Enum
FLAGS = flags.FLAGS

def main(argv_):
    if FLAGS.color == Color.RED:
        print('color is red')

if __name__ == '__main__':
    app.run(main)

and,

$ python main.py --color red
color is red
yilei commented 1 year ago

Enum classes are supported by a separate function flags.DEFINE_enum_class. Does this work for you?

TRSasasusu commented 1 year ago

Thank you, @yilei !! I'm surprised that there is flags.DEFINE_enum_class, which is not written in the document... (but exists in _defines.py)

Now, main.py:

from enum import Enum, auto
from absl import app, flags

class Color(Enum):
    RED = auto()
    GREEN = auto()

flags.DEFINE_enum_class('color', Color.RED, Color, 'set color')
FLAGS = flags.FLAGS

def main(argv_):
    if FLAGS.color == Color.RED:
        print('color is red')

if __name__ == '__main__':
    app.run(main)

and,

$ python main.py --help

       USAGE: main.py [flags]
flags:

main.py:
  --color: <red|green>: set color
    (default: 'red')

Try --helpfull to get a list of all flags.
$ python main.py --color red
color is red

It works well. Thanks!

annulen commented 7 months ago

I also find it confusing that flags.DEFINE_enum_class is missing in online docs. It's very easy to miss, as one not aware of DEFINE_enum_class can use e.g. list(Color) while deriving Color from StrEnum with DEFINE_enum, and it will work fine until case-sensitivity issues arise.

What is the proper way to update contents of https://abseil.io/docs/python/guides/flags?