位置“*”得到一些特殊处理。它的nargs 对空列表(无)感到满意。它总是被处理。对照choices 检查一个空的字符串列表是什么意思?
所以get_values() 方法可以:
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
其中_check_value 测试value 是否在choices 中。
这样的位置最好与有效的default 一起使用。
In [729]: p=argparse.ArgumentParser()
In [730]: a=p.add_argument("FLAGS", nargs='*', choices=["X","Y","Z","ALL"])
In [731]: p.parse_args([])
usage: ipython3 [-h] [{X,Y,Z,ALL} [{X,Y,Z,ALL} ...]]
ipython3: error: argument FLAGS: invalid choice: [] (choose from 'X', 'Y', 'Z', 'ALL')
...
针对choices 测试空列表失败:
In [732]: a.choices
Out[732]: ['X', 'Y', 'Z', 'ALL']
In [733]: [] in a.choices
Out[733]: False
In [734]: 'X' in a.choices
Out[734]: True
如果我们设置一个有效的默认值:
In [735]: a.default='X'
In [736]: p.parse_args([])
Out[736]: Namespace(FLAGS='X')
这种行为是允许我们在mutually_exclusive_group 中使用这种定位的部分原因。
如果您不想指定有效的默认值,则将其更改为标记参数可以避免问题。