You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Incorrect interaction between argparse nargs='*' and choices #92445
Could you please elaborate the expected behavior here ?
I believe the expected behaviour for passing an empty list with nargs="*" should be the same behaviour as passing an empty list with nargs="?" since * is 0 or more arguments whereas ? is 0 or 1 arguments.
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> p.add_argument('dessert', nargs="?", choices=('cake', 'pie'))
>>> p.parse_args([])
Namespace(dessert=None)
This only happens for a positional. nargs='*' (and '?') gets some special handling in get_values, when an emply list satisfies its nargs. The default is assigned in place of the empty list.
This is part of the logic that allows us to use these positionals in a mutually_exclusive_group.
Activity
AbhigyanBose commentedon May 9, 2022
@rhettinger
Could you please elaborate the expected behavior here ?
I tested this on 3.8 and the main branch. In both
p.parse_args([])gives us the same result as calling the script without any arguments.Could you tell me the expected output should the code snippet you shared(also pasted below) be run without any arguments?
Harry-Lees commentedon May 9, 2022
I believe the expected behaviour for passing an empty list with
nargs="*"should be the same behaviour as passing an empty list withnargs="?"since*is 0 or more arguments whereas?is 0 or 1 arguments.hpaulj commentedon May 10, 2022
This only happens for a
positional.nargs='*'(and '?') gets some special handling inget_values, when an emply list satisfies itsnargs. Thedefaultis assigned in place of the empty list.This is part of the logic that allows us to use these
positionalsin amutually_exclusive_group.gh-92445 Improve interaction between nargs="*" and choices() (GH-92565)