Skip to content

argparse drops "|" when a positional, then a special "-" argument (order-sensitive), are defined in a mutually exclusive group #113008

@keeeeymann

Description

@keeeeymann

Bug report

Bug description:

I'm defining a argparse parser that works like vim:

support a file as a positional:

vim file.py

or reading from stdin:

cat file.py | vim -

So I write a mutually exclusive group:

import argparse
ap = argparse.ArgumentParser(description="fake vim")
mg = ap.add_mutually_exclusive_group(required=True)
mg.add_argument("input", nargs="?")
mg.add_argument("-", dest="from_stdin", action="store_true")
args = ap.parse_args()

When I use "-h" to show the help message, the "|" in usage line is dropped, as if the 2 arguments are not mutually exclusive:

usage: fake_vim.py [-h] [-] [input]

However, if I swap the 2 add_argument lines in the source code:

import argparse
ap = argparse.ArgumentParser(description="fake vim")
mg = ap.add_mutually_exclusive_group(required=True)
mg.add_argument("-", dest="from_stdin", action="store_true")
mg.add_argument("input", nargs="?")
args = ap.parse_args()

It magically behaves correctly:

usage: fake_vim.py [-h] (- | input)

CPython versions tested on:

3.9, 3.11

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions