Is there a way to produce the equivalent of const (that we can use with nargs='?', see reference question here for an example), but for nargs='*'. Meaning that I would want:
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument('--option', nargs='*', const=[1, 2, 3])
print(argparser.parse_args())
And then during usage:
my_script.py # Namespace(option=None)
my_script.py --option # Namespace(option=[1, 2, 3])
my_script.py --option 4 5 # Namespace(option=[4, 5])
Currently I get ValueError: nargs must be '?' to supply const
constthe second case should produceoption=[]. You could easily detect and replace that after parsing.storeAction class "if const is not None and nargs != OPTIONAL:". In_get_values'OPTIONAL' has a special step to handleconst. Othernargsdo not._get_valuesis called before theAction's__call__.constis more straightforward. Why is argparse not enabling const with*? It's just inconsistent...const. I don't know the thinking of the original developer, but my guess is theconst` was included for use by 'store_const' and its sublclass 'store_true'.. Its use in the 3 way '?' is a bonus. Ifargparsedoesn't do everything you want it's perfect ok (even encouraged) to write a custom action class, or to do your own post-parsing checking.[]is that a) we can't usedefault=[]anymore; b) We rely on the detail ofnargs="*"producing a list, not a tuple. So you'd have to doif args.myarg is None: {default}; elif not args.myarg: {const}. Not very idiomatic IMO.