Repository navigation
Closed
Labels
3.7 (EOL)end of lifestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Description
| BPO | 14191 |
|---|---|
| Nosy | @bitdancer, @vadmium, @monkeyman79 |
| PRs | |
| Files |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = None
closed_at = <Date 2017-09-07.00:27:33.235>
created_at = <Date 2012-03-04.06:36:30.660>
labels = ['3.7', 'type-feature', 'library']
title = "argparse doesn't allow optionals within positionals"
updated_at = <Date 2021-01-29.13:29:51.106>
user = 'https://bugs.python.org/vpython'bugs.python.org fields:
activity = <Date 2021-01-29.13:29:51.106>
actor = 'monkeyman79'
assignee = 'none'
closed = True
closed_date = <Date 2017-09-07.00:27:33.235>
closer = 'r.david.murray'
components = ['Library (Lib)']
creation = <Date 2012-03-04.06:36:30.660>
creator = 'v+python'
dependencies = []
files = ['24726', '24745', '24749', '24753', '24764', '24771', '26273', '29982', '30159', '30160', '30204', '30422']
hgrepos = []
issue_num = 14191
keywords = ['patch']
message_count = 47.0
messages = ['154880', '155008', '155019', '155039', '155062', '155103', '155157', '155172', '155185', '155188', '155202', '155212', '155272', '155277', '164756', '166175', '166193', '185517', '187051', '187269', '187270', '187329', '187341', '187596', '187618', '187669', '187680', '188608', '188609', '188680', '188869', '188871', '188887', '188899', '190339', '190340', '195312', '195728', '195740', '196067', '196110', '217812', '301275', '301292', '301415', '301549', '301550']
nosy_count = 10.0
nosy_names = ['amcnabb', 'bethard', 'v+python', 'r.david.murray', 'docs@python', 'martin.panter', 'paul.j3', 'guilherme-pg', 'dg1727', 'monkeyman79']
pr_nums = ['3319', '24259', '24367']
priority = 'normal'
resolution = 'fixed'
stage = 'resolved'
status = 'closed'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue14191'
versions = ['Python 3.7']Metadata
Metadata
Assignees
Labels
3.7 (EOL)end of lifestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Activity
vpython commentedon Mar 4, 2012
To me, "all positional parameters" mean whether they are in the front, back or middle, as long as they are not diriectly preceded by an option that can accept an unlimited number of parameters.
Above also supplied as a test file, t12.py
[-]argparse: nargs='*' doesn't parse all positional parameters[/-][+]argparse: nargs='*' doesn't get out-of-order positional parameters[/+]bethard commentedon Mar 6, 2012
This behavior is intentional - positional arguments must be sequential, not broken up with optional (flag) arguments between. So this is a documentation bug.
Allowing positional arguments to be broken up with optional (flag) arguments between them would be a new feature. It would also break many current parsers, so it couldn't be turned on by default. A new constructor parameter or method or something would have to be added to ArgumentParser. Patches welcome.
guilherme-pg commentedon Mar 6, 2012
I uploaded an incomplete patch that might address the issue so it can be discussed.
This patch introduces 'greedy_star', a new constructor parameter to ArgumentParser that makes "*" positional arguments behave as expected in the test case.
The patch doesn't yet update the documentation and doesn't include test cases, but I'll be glad to provide those changes in a next version.
It is admittedly hackish, but I haven't found a better solution so far. Looking forward for your comments.
vpython commentedon Mar 6, 2012
Interesting that the behavior is intentional, yet it accepts positional parameters either before, or after, or between optional (flag) parameters.
This seems to me to be a case where proper documentation of the intention would have led to the realization that it is easier to fix the code than the documentation.
The only definition of positional parameters I could find in the present documentation is:
When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional:
This is simple and succinct, but leads to my interpretation that they can be anywhere, intermixed with optional arguments.
Further, optparse, which argparse attempts to replace, permitted positional arguments to be intermixed with optional arguments, see new file t13.py which demonstrates that.
To document that positional parameters must be grouped together, yet can appear anywhere, the documentation would have to get much more verbose... something like
All positional parameters must be grouped together in a single sequence. However, that group of parameters may have optional parameters either before it or after it, or there may be optional parameter both before it and after it.
bethard commentedon Mar 7, 2012
Sure, but optparse didn't actually parse positional arguments - it just threw them into a bag, and then you had to group them and convert them however you wanted afterwards. Argparse, instead, was designed to let you specify the groups of positional arguments. Your situation is a little different because you just want to throw all the positional arguments into a bag again. Not that there's anything wrong with that - it's just not the primary use case argparse had in mind.
Yeah, it looks like there's no good documentation on positional vs. optional parameters. Somewhere obvious, perhaps right at the beginning of the add_argument() documentation, there should probably be something like:
Argparse groups the command line argument strings into two types of groups: optional arguments, which are a sequence of command line strings that begin with a flag like "-v" or "--verbose", and positional arguments, which are a sequence of command line strings that do not begin with a flag. The add_argument() method allows you to specify how many command line strings each of your optional or positional arguments should consume, how those strings should be converted into Python objects, etc.
vpython commentedon Mar 7, 2012
Improved documentation would certainly help the situation.
And yes, I understand that optparse simply returned the set of positional parameters without giving them names, types, or groups. So does getopt, and pretty much all previous art in the arena of command line parsing that I am familiar with.
To successfully replace optparse and other prior art, though, there should be an equivalent, although perhaps improved, functionality in argparse.
This lack of documentation for the idea that the ordered set of all positional parameters is not treated as a sequence certainly slipped under the covers of optparse functionality when I first read about it when optparse was being added to the stdlib. I had no clue that the specification of positional parameters would do anything other than process the positional parameters sequentially, without being disrupted by intervening optional parameters. The capabilities for naming, and typing those parameters are nice enhancements, but were not seen as redefining what positional parameters are, from its historical definition. Is there wording in the PEP that describes such?
Naming and typing and even grouping positional parameters are all nice features... but there should be no undocumented boundaries between positional parameters (or groups of them), and presently there are no documented boundaries, and with prior art there were no boundaries.
Having no boundaries among positional parameters is a capability and expectation that has a long history, and tools ported from prior art to argparse need the capability to preserve command line compatibility. Hence, I conclude that, unless this was spelled out in the PEP and I missed it, that having such boundaries is a bug, even if your intentions were otherwise, and that the test case I provided should work.
My test was only meant to demonstrate the issue, not to be a particular use case, but there are use cases that would be affected in the same manner as the demonstration.
Regarding your suggested documentation, it is more complete than my suggestion, but "sequence" should probably be replaced by "sequence of adjacent" if that is what is meant, because with positional parameters, the historical perspective is that the sequence of positional parameters may be interrupted by optional parameters, but that makes it no less a sequence.
I believe that the present syntax for parsing positional parameters should be fixed to handle all positional parameters, because of the history of prior art, and that if there is a need, benefit, or demand for treating positional parameters in groups, then that should be documented and created as additional features.
I further cannot figure out how to even parse the additional positional parameters as a separate group, using the current capabilities. My attempt to do so in t14.py failed.
bethard commentedon Mar 8, 2012
Practically speaking, we just can't change this because it will break existing argparse scripts. Argparse has had this behavior since 2006 when it was first released, and I guarantee you that many scripts expect and rely on this behavior.
As I said earlier, the only reasonable solution is to document the current behavior more explicitly, and then add a new constructor parameter or method or something to enable the behavior you want.
I looked a bit a guilherme's patch, and I think it's not really the right direction. We definitely shouldn't be modifying the action classes like _StoreAction. All changes should be within _parse_known_args. The parsing algorithm is so different for the proposed behavior, that I wonder if it wouldn't be easier to just create a new ArgumentParser subclass, ArgumentParserAllowingOptionalsInsidePositionals (or whatever), that just overrides _parse_known_args and rewrites it entirely.
vpython commentedon Mar 8, 2012
Ah yes, argparse had a life outside the stdlib, so now I understand your compatibility concerns.
Mind you, I think the overall technology of argparse is superior to optparse, which is why, together with the optparse deprecation, I am trying to port to use it... so consider me a fan, not an enemy. But...
However, it seems that while the esoteric extensions required in optparse were a known incompatibility at the time the PEP was written, the incompatibility with intermixed positional and optional parameters slipped under the radar... but is actually a more serious compatibility problem for general use.
I see three possible ways forward, maybe there are others.
un-deprecate optparse, explaining and documenting this functional difference between optparse and argparse. The deprecation of optparse is what makes this missing capability a bug, rather than a feature enhancement.
add features to argparse to make it capable of parsing all the same command lines as unextended optparse. (I'm of the opinion that folks that extended optparse can learn to extend argparse in similar or more capable manners; not having such extensions, I'm not qualified to state whether there are optparse extensions that cannot be ported to use standard or extended argparse capabilities.) The documentation for such features should clearly state that former users of argparse may be interested in using this feature, and should state why; further, the deprecation notice in optparse should be updated to point out that porting to argparse may need to use this particular argparse capability to achieve command line compatibility with optparse, and that the capability is not available until (specified release).
If there is an already existing way (my t14.py is a half-hearted attempt to find it) to parse scattered positional parameters, it could be explicitly documented rather than writing new capabilities per Rename README to README.rst and enhance formatting #2. However, since you as author jumped to the new capabilities option straightway, I suspect this is not really a possibility.
The rest of this is concerned option #2, which seems the best way forward to me, with my current knowledge.
You mention ArgumentParserAllowingOptionalsInsidePositionals and that is extremely lengthy, might I suggest something like ArgumentParserIntermixed ?
What would be the scope of the effort, and what release(s) might be a possible target? (since it is a bug, it can be backported, but since the cure will be implemented as a new capability, that might be problematical for point releases, somehow? I'm not the expert in that area.)
bethard commentedon Mar 8, 2012
Thinking about it a bit more, it strikes me that maybe you could get the behavior you want by declaring two parsers, one with just optionals, and one with just positionals. Then:
optional_args, remaining_args = optionals.parse_known_args()
args = positionals.parse_args(remaining_args)
vars(args).update(vars(optional_args))
Basically, you first parse out all the optional arguments, then you parse out the positional arguments from what's left after the optional arguments are stripped out. This approach seems to work for your t14.py.
bethard commentedon Mar 8, 2012
Actually, that could be even simpler:
args, remaining_args = optionals.parse_known_args()
args = positionals.parse_args(remaining_args, args)
vpython commentedon Mar 9, 2012
*Very* interesting, Steven.
Looking again at section 15.4.6, and recognizing that positional arguments were never parsed by optparse, then we discover that with two minor tweaks, removing "and add additional ArgumentParser.add_argument() calls for the positional arguments." from step two, and calling parse_known_args instead of parse_args, we actually achieve greater compatibility with optparse, for those that need it.
However, the above would allow undefined arguments to slip through into the positional arguments.
So to prevent that, the second parser you suggest, defining only the positional arguments, will tighten up the error checks.
So this issue could be resolved simply by updating section 15.4.6 of the documentation to explain all this. On the other hand, the explanation gets long and perhaps confusing.
Looking at the 15.4.4, I see:
However, nowhere is the args= parameter explained. One example is given at the end of 15.4.4.6 showing the use of args= which apparently accepts a list of parameters, similar to the positional list of parameters that are used in all the other examples. It might be nice to clarify that.
This leads into a suggestion: a new keyword parameter for parse_args: intermixed=False.
When False, the default, new_parse_args would act exactly as it does today, possibly by calling old_parse_args. When True, parse_args would implement your suggestion probably in the following way: filter out the positional parameters, call parse_known_args, then filter out the optional parameters, call old_parse_args, and return the combination.
t16.py implements this, external to the class, and using two parsers as you suggested.
One thing I notice in playing with my optparse function, is that error messages contain an improper usage message. This would seem to be most easily fixed if the logic were built in to argparse, rather than attempting to do it externally.
Adding this parameter would also make it is much easier to write section 15.4.7 accurately, and would reduce the porting burden on each implementer, as well. The technique has merit in achieving compatibility with optparse, to allow it to remain deprecated, and looks straightforward to implement.
bitdancer commentedon Mar 9, 2012
To answer Glenn's procedural question: no this is not a bug whose fix can be backported. API changes are not allowed in maintenance releases. Doc improvements can be backported, though, so I'm leaving versios alone (alternatively someone could split this into two bugs, one for the doc fixes for older releases, and one for adding the new capability).
30 remaining items
paulj3 commentedon Aug 20, 2013
It's everything I intend to add. Now I'm just waiting for a committer to act, either with suggested changes, or a merge. I'm watching more than a dozen argparse patches.
vpython commentedon Aug 21, 2013
So I read over your code again, and even read the documentation this time, and it all looks good, and I know it works good because I've been using the code. I tried to send a notice through Reitveld, and maybe did, but I don't know where it went, so I'll say this much here, too.
vadmium commentedon Aug 24, 2013
It sounds like this bug might cover bpo-15112, which is only concerned with options between different positional parameters.
paulj3 commentedon Aug 25, 2013
Above in
http://bugs.python.org/issue14191#msg187051
I proposed a patch that is quite close to bethard's patch in http://bugs.python.org/issue15112#msg166173
Both modify the same place, doing the same (pop items off arg_counts). The logic is a little different. I'd have to look at them more carefully to see whether one is more robust. Thanks for linking that issue.
The main issue here is different, allowing for complete intermixing of optionals and positionals. Over at 15112 the issue is intermixing of optionals and 'whole' positionals. My 187051 patch belongs over there.
paulj3 commentedon May 3, 2014
I encountered a conflict when merging this patch with http://bugs.python.org/issue15112. In my first testcase, 'cmd' and 'rest' failed the 'required' test in phase one of 'intermixed'. That's because 15112 postponed parsing them (with nargs=0/suppressed).
I got around that by temporarily setting the 'required' attribute to False.
The whole issue of when (or even whether) a positional that is satisfied with 0 arguments, is consumed, is a bit messy.
bitdancer commentedon Sep 4, 2017
I've turned intermixed.patch into a PR. I tweaked the documentation so that it does not refer to the details of the implementation. I tweaked the implementation to have the 'try' start before the code that modifies the state, and did the line wrapping to <80 columns.
I have one concern about this patch: parse_intermixed_args doesn't support all of the argparse features. It feels to me like it is worthwhile to add anyway, and maybe someone will figure out how to support more features later. But I'd like at least one other committer to concur :)
Given concurrence I'll add news and what's new entries.
paul.j3: I'm trying to review argparse patches during this core sprint week, so if you have anything in particular you want me to focus on, please let me know.
vpython commentedon Sep 5, 2017
I would dearly love to discard my private copies of argparse subclasses to implement this that I have been using for the last 5 years. Please, some other committer, concur here!
bitdancer commentedon Sep 6, 2017
I got an offline agreement from Zach Ware, and nobody here at the sprint has objected (though I don't know if anyone else looked), so I'll go ahead and finish the PR.
bitdancer commentedon Sep 7, 2017
New changeset 0f6b9d2 by R. David Murray in branch 'master':
bpo-14191 Add parse_intermixed_args. (bpo-3319)
0f6b9d2
bitdancer commentedon Sep 7, 2017
Thanks Paul. By the way, if you want your "real name" in What's New, just let me know what it is and I'll make the change.