Do you realize that `choices` can be a dictionary? And since you want the user to supply a key, not a value, you might not want to use a type that does the conversion.
To illustrate consider two ways of using a simple dictionary.
import argparse
adict = {'a': [1,2,3], 'b': 'astring'}
parser = argparse.ArgumentParser()
parser.add_argument('-f',
type = lambda x: adict.get(x,x),
choices = list(adict.values())
)
parser.add_argument('-g', choices = adict)
args = parser.parse_args()
print(args)
print(args.f, adict[args.g])
sample runs:
valid key:
0942:~/mypy$ python3 issue42191.py -f a -g a
Namespace(f=[1, 2, 3], g='a')
[1, 2, 3] [1, 2, 3]
help:
0945:~/mypy$ python3 issue42191.py -h
usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]
optional arguments:
-h, --help show this help message and exit
-f {[1, 2, 3],astring}
-g {a,b}
Error cases:
0945:~/mypy$ python3 issue42191.py -f x
usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]
issue42191.py: error: argument -f: invalid choice: 'x' (choose from
[1, 2, 3], 'astring')
0945:~/mypy$ python3 issue42191.py -g x
usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]
issue42191.py: error: argument -g: invalid choice: 'x' (choose from
'a', 'b')
With -g, we have to perform the dictionary lookup after parsing, but choices, {a,b}, are clear in both the help and error.
With -f, both the help (which uses str) and the error, give wrong user choices, the dictionary values rather than the keys.
|