Skip to content

Incorrect interaction between argparse nargs='*' and choices #92445

Closed

Description

@rhettinger

In the code below, it is valid to supply no arguments.

from argparse import ArgumentParser

p = ArgumentParser()
p.add_argument('dessert', nargs='*', choices=('cake', 'pie'))
p.parse_args([])

However, the following error is generated:

usage: tmp5.py [-h] [{cake,pie} ...]
tmp5.py: error: argument dessert: invalid choice: [] (choose from 'cake', 'pie')

What is happening is that the empty list is being treated a value rather than a collection of values.

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    3.11only security fixes
    3.12only security fixes
    on May 8, 2022
  2. AbhigyanBose commented on May 9, 2022

    @AbhigyanBose
    Contributor

    @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?

    from argparse import ArgumentParser
    
    p = ArgumentParser()
    p.add_argument('dessert', nargs='*', choices=('cake', 'pie'))
    p.parse_args([])
    
  3. Harry-Lees commented on May 9, 2022

    @Harry-Lees
    Contributor

    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)
    
  4. hpaulj commented on May 10, 2022

    @hpaulj

    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.

  5. Repository owner moved this from Bugs to Doc issues in Argparse issueson Aug 25, 2022
  6. added a commit that references this issue on Aug 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.10 (EOL)end of life3.11only security fixes3.12only security fixes3.9 (EOL)end of lifeeasystdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions