enumaction
Argparse action for using enum as a choice.
Rationale
Why would you want to do this if there is already the choice argument available? Choice limits you to a set of strings which means you get to maintain a list of valid strings through your application. If you use an enum, the information will all be in one place.
Usage
Using EnumAction is a simple process involving 3 steps.
Define an enum subclass with your choices.
class FooEnum(enum.Enum):
Foo = 'foo'
Bar = 'bar'
The enum can be a subclass of Enum, Flag,
FlagInt, and IntEnum.
2. Add an argument to the parser and specify a kwarg type with the enum subclass as value and action with value EnumAction. Optionally, add a kwarg use with value name [default] or value to use the enum name or value, respectively, to match the argument to an enum member.
Note
If you subclass Enum, you can use name or value.
All other enum types (e.g. Flag, FlagInt, and
IntEnum) only work with name.
parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', type=FooEnum, action=EnumAction)
parser.add_argument('--bar', '-b', type=FooEnum, use='value', action=EnumAction)
Finally, call the
parse_args()method of the parser.
Inspired by https://stackoverflow.com/a/60750535.
New in version 1.7.0.
- class pymisclib.enumaction.EnumAction(**kwargs)
Argparse action for handling Enums
- __init__(**kwargs)
Initialize the instance.
- Keyword arguments:
type Specify an :py:type:`enum.Enum` subclass. [required]
use Either “name” or “value”. [optional]