Skip to content

argparse.BooleanOptionalAction silently failed when used with parser whose prefix_chars has no '-' #138525

@mattwang44

Description

@mattwang44

Bug report

Bug description:

argparse.BooleanOptionalAction (doc) handles the creation of the boolean flags with positive and negative options by having user only needs to add the positive argument. However, it only works with those parsers whose prefix_chars contains '-', which is the default value, and otherwise failed to create the negative option silently.

>>> from argparse import BooleanOptionalAction, ArgumentParser
>>> # normal usage
>>> p = ArgumentParser()  # prefix_chars defaults to '-'
>>> p.add_argument("--foo", action=BooleanOptionalAction)
BooleanOptionalAction(option_strings=['--foo', '--no-foo'], dest='foo', nargs=0, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> p.parse_args(['--no-foo'])
Namespace(foo=False)
>>>
>>> # parser with customized prefix_chars
>>> p = ArgumentParser(prefix_chars='+')
>>> p.add_argument("++foo", action=BooleanOptionalAction)
BooleanOptionalAction(option_strings=['++foo'], dest='foo', nargs=0, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)

Raising warning/error is expected when argparse.BooleanOptionalAction is used with parsers whose prefix_chars has no '-'.

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions