Skip to content

argparse nargs=-1 fails on python 3.12.7 #126708

Closed as not planned
Closed as not planned
@ikappaki

Description

@ikappaki

Bug report

Bug description:

It seems there's a pattern in the wild with argparse where nargs=-1 is used to capture the remaining command line arguments. However, I couldn’t find anything in the argparse nargs documentation to indicate that this is a supported feature, though it appears to be widely used: https://grep.app/search?current=4&q=nargs%3D-1&filter[lang][0]=Python

This pattern has stopped working as of Python v3.12.7, likely due to #124631 which doesn't appear to have made it to v3.13.0, but it has been backported to the 3.13 branch.

To reproduce,

  1. Create an issue.py file
import argparse
import sys
print(f":version {sys.version}")
parser = argparse.ArgumentParser()
parser.add_argument("args", nargs=-1)
parsed_args, extra = parser.parse_known_args()
print(f":args {parsed_args} :extra {extra}")
  1. and run it with python 3.12.7, you should get a the following arguments are required error.
$ d:/local/Python312/python.exe issue.py 5 6
usage: issue.py [-h]
issue.py: error: the following arguments are required: args
:version 3.12.7 (tags/v3.12.7:0b05ead, Oct  1 2024, 03:06:41) [MSC v.1941 64 bit (AMD64)]

The same works with any other version at the momenet, for example 3.11 or 3.13:

$ python.exe issue.py 5 6
:version 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)]
:args Namespace(args=[]) :extra ['5', '6']

$ d:/local/Python313/python.exe issue.py 5 6
:version 3.13.0 (tags/v3.13.0:60403a5, Oct  7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)]
:args Namespace(args=[]) :extra ['5', '6']

Could you please take a look and advise whether this is something you might want to continue supporting, or if there are alternative approaches you would recommend?

I don't personally use this pattern, but I came across it and thought it would be helpful to report, as it might assist developers in making informed decisions about it.

Thanks

CPython versions tested on:

3.12, CPython main branch

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibPython 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