Skip to content

Inconsistent argparse ArgumentParser parse_known_args() behavior when '--' is present in argument list #136462

Closed as not planned
@Valentin2208

Description

@Valentin2208

Bug report

Bug description:

parser.parse_known_args() behavior is inconsistent when '--' is present in argument list.
It ends up in extras if last known argument is an optional.

import argparse
p = argparse.ArgumentParser()
p.add_argument('a')
p.add_argument('b')
p.add_argument('--qwe', required=False)
print(p.parse_known_args(['a', 'b', '--qwe', 'qwe', '--', 'c', '--d', '--qwe', 'asd']))

# OUTPUT:   (Namespace(a='a', b='b', qwe='qwe'), ['--', 'c', '--d', '--qwe', 'asd'])
# Expected: (Namespace(a='a', b='b', qwe='qwe'), ['c', '--d', '--qwe', 'asd'])

However, if last known argument is positional, then '--' is not present in extras, as expected.

import argparse
p = argparse.ArgumentParser()
p.add_argument('a')
p.add_argument('b')
p.add_argument('--qwe', required=False)
print(p.parse_known_args(['--qwe', 'qwe', 'a', 'b', '--', 'c', '--d', '--qwe', 'asd']))

# OUTPUT: (Namespace(a='a', b='b', qwe='qwe'), ['c', '--d', '--qwe', 'asd'])

Seems like it happens because '--' is consumed along with positional argument in consume_positionals(), because self._match_arguments_partial() uses 'A-' pattern for that case.

CPython versions tested on:

3.10, 3.11, 3.12

Operating systems tested on:

Windows, Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy