In argparse
, how can I create an optional positional command line option that takes multiple arguments which all need to be part of a list of choices?
In the following example, I want to allow any subset of the list ['a', 'b', 'c']
– i.e. ['a']
, ['a', 'c']
, ... and, crucially, the empty list []
. I was expecting the following to achieve that, but it fails if the argument is omitted.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('letters', nargs='*', choices=['a', 'b', 'c'])
args = parser.parse_args()
error: argument letters: invalid choice: [] (choose from 'a', 'b', 'c')
UPDATE: I have since found that choices=['a', 'b', 'c', []]
appears to do the job. That strikes me as inconsistent as it suggests that argparse
checks for [] in choices
which would then imply that ['a']
should be in choices
as well (rather than 'a'
).