You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
argparse.REMAINDER fails to parse remainder correctly #58382
Reproduction case is attached and should speak for itself, but the short brief is that the argparse.REMAINDER behaviour is very inconsistent based on what (potentially) defined argument handlers come before it.
Tested this on Python 2.7 on OS X, but also grabbed the latest argparse.py from hg to verify against this.
I'm attaching my own bug repro script for Eric. Is this sufficient? I can demonstrate the entire resulting Namespace, but the problem is that argparse doesn't even produce a Namespace. The cases I show simply fail.
When you have several positionals, one or more of which may have 0 arguments (*,?,...), it is best to put all of the optional arguments first.
With 'app --config bar', parse_args identifies a 'AOA' pattern (argument, optional, argument). It then checks which positional arguments match. 'app' claims 1, 'app_args' claims 2 (REMAINDER means match everything that follows). That leaves nothing for '--config'.
What you expected was that 'app' would match with the 1st string, '--config' would match the next 2, leaving nothing for 'app_args'.
In http://bugs.python.org/issue14191 I wrote a patch that would give the results you want if 'app_args' uses '*'. That is makes it possible to interleave positional and optional argument strings. But it does not change the behavior of REMAINDER.
parser.add_argument('app_args', nargs='*')
Maybe the documentation example for REMAINDER needs to modified to show just how 'greedy' REMAINDER is. Adding a:
parser.add_argument('--arg1',action='store_true')
does not change the outcome. REMAINDER still grabs '--arg1' even though it is a defined argument.
By the way, parser.parse_args() uses parse_known_arg(). parse_known_args returns a Namespace and a list of unknown arguments. If that list is empty, parse_args returns the Namespace. If the list is not empty, parse_args raises an error.
So parse_known_args does not change how arguments are parsed. It just changes how the unknowns are handled.
paulj3 commented on Jul 2, 2014
paulj3mannequin
Mannequin
More actions
Here's a possible solution to the problem (assuming there really is one):
redefine REMAINDER so it matches a '((?:A[AO]*)?)' pattern (where O is a string that looks like an optional flag, A an argument string). I've added the condition that the first match (if any) must be an A. It ends up being closer to the pattern for PARSER.
I included a patch from bpo-15112, which delays the consumption of a positional that matches with 0 strings.
In the sample case for this issue, results with this patch are:
In the last case, 'app_args' gets the rest of the strings because the first is a plain 'args'. I believe this is consistent with the intuition expressed in this issue.
I've added one test case to test_argparse.TestNargsRemainder. This is a TestCase that is similar to the above example.
argument_signatures= [Sig('x'), Sig('y', nargs='...'), Sig('-z')]
failures= ['', '-z', '-z Z']
successes= [
('X', NS(x='X', y=[], z=None)),
('-z Z X', NS(x='X', y=[], z='Z')),
('X A B -z Z', NS(x='X', y=['A', 'B', '-z', 'Z'], z=None)),
('X Y --foo', NS(x='X', y=['Y', '--foo'], z=None)),
('X -z Z A B', NS(x='X', y=['A', 'B'], z='Z')), # new case
]
This patch runs test_argparse fine. But there is a slight possibility that this patch will cause backward compatibility problems. Some user might expect y=['-z','Z',...]. But that expectation has not been enshrined the test_argparse.
It may require a slight change to the documentation as well.
I am not really sure that this is a bug. REMAINDER can be used to simulate a subparser if you cannot use standard subparsers for some reasons (for example if the syntax of the subparser is not known at that level). The original example is such a case. app_args can contain positional and optional arguments for app (you would use nargs='*' if it can contain only positional arguments). It can contain option --config. Therefore it should be considered a part of app_args if it is specified after apps. This looks reasonable.
If redefine REMAINDER so that the first match must be not option, we could use "--" to pass an option as the first item in REMAINDER (except "--"): app -- --config bar. We cannot use this if REMAINDER is used with option, because arguments of options cannot be "--"). See #66419 which proposes to change this. Together this may work, but it will break some user code.
Note also that REMAINDER is currently undocumented (see bpo-17050/gh-61252). It is now legacy feature. It adds additional pressure against significant changes of its behavior.
I agree with Serhiy’s reasoning here. Although it's a bit surprising, consuming recognized options after the command name would break forwarding cases where the invoked command uses the same option names as the outer parser. Outer options can be supplied before the command name.
I’m closing this as not planned to preserve that behavior. I’ve also opened #160119 to redocument REMAINDER, including this boundary and an example showing it explicitly.
Activity
rr2do2 commentedon Mar 2, 2012
Reproduction case is attached and should speak for itself, but the short brief is that the argparse.REMAINDER behaviour is very inconsistent based on what (potentially) defined argument handlers come before it.
Tested this on Python 2.7 on OS X, but also grabbed the latest argparse.py from hg to verify against this.
merwok commentedon Mar 5, 2012
Thanks for the report. Could you edit your script to add the expected results, for example Namespace(foo=..., command=[...])?
idank commentedon Sep 21, 2012
I just ran into this issue myself and worked around it by using parse_known_args*.
jaraco commentedon Oct 6, 2012
I also ran into this problem. I put together this script to reproduce the issue:
I'll try using parse_known_args instead.
idank commentedon Oct 6, 2012
Unfortunately parse_known_args is buggy too: http://bugs.python.org/issue16142
MichaelEdwards commentedon Nov 30, 2012
I'm attaching my own bug repro script for Eric. Is this sufficient? I can demonstrate the entire resulting Namespace, but the problem is that argparse doesn't even produce a Namespace. The cases I show simply fail.
cjerdonek commentedon Jan 27, 2013
See also bpo-17050 for a reduced/simple case where argparse.REMAINDER doesn't work (the case of the first argument being argparse.REMAINDER).
paulj3 commentedon Apr 17, 2013
An alternative to Jason's example:
When you have several positionals, one or more of which may have 0 arguments (*,?,...), it is best to put all of the optional arguments first.
With 'app --config bar', parse_args identifies a 'AOA' pattern (argument, optional, argument). It then checks which positional arguments match. 'app' claims 1, 'app_args' claims 2 (REMAINDER means match everything that follows). That leaves nothing for '--config'.
What you expected was that 'app' would match with the 1st string, '--config' would match the next 2, leaving nothing for 'app_args'.
In http://bugs.python.org/issue14191 I wrote a patch that would give the results you want if 'app_args' uses '*'. That is makes it possible to interleave positional and optional argument strings. But it does not change the behavior of REMAINDER.
Maybe the documentation example for REMAINDER needs to modified to show just how 'greedy' REMAINDER is. Adding a:
does not change the outcome. REMAINDER still grabs '--arg1' even though it is a defined argument.
paulj3 commentedon Apr 17, 2013
By the way, parser.parse_args() uses parse_known_arg(). parse_known_args returns a Namespace and a list of unknown arguments. If that list is empty, parse_args returns the Namespace. If the list is not empty, parse_args raises an error.
So parse_known_args does not change how arguments are parsed. It just changes how the unknowns are handled.
paulj3 commentedon Jul 2, 2014
Here's a possible solution to the problem (assuming there really is one):
I included a patch from bpo-15112, which delays the consumption of a positional that matches with 0 strings.
In the sample case for this issue, results with this patch are:
In the last case, 'app_args' gets the rest of the strings because the first is a plain 'args'. I believe this is consistent with the intuition expressed in this issue.
I've added one test case to test_argparse.TestNargsRemainder. This is a TestCase that is similar to the above example.
This patch runs test_argparse fine. But there is a slight possibility that this patch will cause backward compatibility problems. Some user might expect y=['-z','Z',...]. But that expectation has not been enshrined the test_argparse.
It may require a slight change to the documentation as well.
serhiy-storchaka commentedon Sep 24, 2024
I am not really sure that this is a bug. REMAINDER can be used to simulate a subparser if you cannot use standard subparsers for some reasons (for example if the syntax of the subparser is not known at that level). The original example is such a case.
app_argscan contain positional and optional arguments forapp(you would usenargs='*'if it can contain only positional arguments). It can contain option--config. Therefore it should be considered a part ofapp_argsif it is specified afterapps. This looks reasonable.If redefine REMAINDER so that the first match must be not option, we could use "--" to pass an option as the first item in REMAINDER (except "--"):
app -- --config bar. We cannot use this if REMAINDER is used with option, because arguments of options cannot be "--"). See #66419 which proposes to change this. Together this may work, but it will break some user code.Note also that REMAINDER is currently undocumented (see bpo-17050/gh-61252). It is now legacy feature. It adds additional pressure against significant changes of its behavior.
savannahostrowski commentedon Oct 21, 2026
I agree with Serhiy’s reasoning here. Although it's a bit surprising, consuming recognized options after the command name would break forwarding cases where the invoked command uses the same option names as the outer parser. Outer options can be supplied before the command name.
I’m closing this as not planned to preserve that behavior. I’ve also opened #160119 to redocument REMAINDER, including this boundary and an example showing it explicitly.