The Wayback Machine - https://web.archive.org/web/20260814185945/https://github.com/python/cpython/issues/121282
Skip to content

argparse mis-handles a store_true option in between two nargs="?" positionals #121282

Description

@zackw

Bug report

Bug description:

Consider the following cut-down script:

import argparse
import pprint

ap = argparse.ArgumentParser()
ap.add_argument("p", nargs="?")
ap.add_argument("q", nargs="?")
ap.add_argument("--test", action="store_true")

args = ap.parse_args()
pprint.pprint(args.__dict__)

When invoked with two positional arguments and --test on either side of them, the behavior is as expected:

$ python3 test.py --test a b
{'p': 'a', 'q': 'b', 'test': True}
$ python3 test.py a b --test
{'p': 'a', 'q': 'b', 'test': True}

However, if you put --test in between the two positionals, argparse misinterprets the argument list:

$ python3 test.py a --test b
usage: test.py [-h] [--test] [p] [q]
test.py: error: unrecognized arguments: b

This argument list should produce the same Namespace object as the first two examples.

CPython versions tested on:

3.9, 3.11, 3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    Status
    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions