Message250429
The `type` parameter is a *function* that takes a string, and returns a valid value. If it can't convert the string it is supposed to raise an error. The default one is a do-nothing identity (take a string, return the string). `int` is the Python function that converts a string to an integer. Same for `float`.
Your example could be implemented with a simple type function:
def enumtype(astring):
try:
return CustomEnumType[astring.upper()]
except KeyError:
raise argparse.ArgumentError()
parser=argparse.ArgumentParser()
parser.add_argument("-p", type=enumtype, default="VAL1")
print(parser.parse_args([]))
print(parser.parse_args(["-p","val2"]))
print(parser.parse_args(["-p","val4"]))
which produces:
1557:~/mypy$ python3 issue25061.py
Namespace(p=<CustomEnumType.VAL1: 1>)
Namespace(p=<CustomEnumType.VAL2: 2>)
usage: issue25061.py [-h] [-p P]
issue25061.py: error: argument -p: invalid enumtype value: 'val4'
The default and 'val2' produce enum values in the Namespace.
'val4' raises an error, resulting in the usage and error message.
I tried to customize the error message to include the list of valid strings, but it looks like I'll have to dig into the calling tree to do that right. Still the default message is useful, displaying the name of the 'type' function.
If we were to add 'enum' support it would have to be something like 'argparse.FileType', a factory class that would take an enum class as parameter, and create a function like my sample. |
|
Date |
User |
Action |
Args |
2015-09-10 23:24:53 | paul.j3 | set | recipients:
+ paul.j3, barry, desbma |
2015-09-10 23:24:53 | paul.j3 | set | messageid: <1441927493.84.0.154136637297.issue25061@psf.upfronthosting.co.za> |
2015-09-10 23:24:53 | paul.j3 | link | issue25061 messages |
2015-09-10 23:24:53 | paul.j3 | create | |
|