-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
argparse assertion failure with brackets in metavars #56083
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I run this script with option --help import argparse
parser = argparse.ArgumentParser()
parser.add_argument ('--from-itm', dest="from_itm",action="store",default=None,help ="Source ITM file", metavar="ITMFILENAME")
parser.add_argument ("--from-fbm-sigtab",dest="from_sigtab",action="store",default=None,help="Source signal FB", metavar=" [LIB,]FBNAME")
parser.add_argument ("--c",dest="f",metavar="x]d")
args = parser.parse_args()
---------8< and I get an assertion failure: D:\temp>argparsebug.py --help
Traceback (most recent call last):
File "D:\temp\argparsebug.py", line 6, in <module>
args = parser.parse_args()
File "C:\Python27\lib\argparse.py", line 1678, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "C:\Python27\lib\argparse.py", line 1710, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "C:\Python27\lib\argparse.py", line 1916, in _parse_known_args
start_index = consume_optional(start_index)
File "C:\Python27\lib\argparse.py", line 1856, in consume_optional
take_action(action, args, option_string)
File "C:\Python27\lib\argparse.py", line 1784, in take_action
action(self, namespace, argument_values, option_string)
File "C:\Python27\lib\argparse.py", line 993, in __call__
parser.print_help()
File "C:\Python27\lib\argparse.py", line 2303, in print_help
self._print_message(self.format_help(), file)
File "C:\Python27\lib\argparse.py", line 2277, in format_help
return formatter.format_help()
File "C:\Python27\lib\argparse.py", line 278, in format_help
help = self._root_section.format_help()
File "C:\Python27\lib\argparse.py", line 208, in format_help
func(*args)
File "C:\Python27\lib\argparse.py", line 329, in _format_usage
assert ' '.join(opt_parts) == opt_usage
AssertionError
--------------8< It must be the combination of several argument lines because when I Is this a bug or do I do things I shouln't? With best regards |
I was a victim of the same issue, but only after my usage list does not fit in one line. Please fix! |
Seem as a problem in optparse.HelpFormatter._format_usage(): when the generated usage string is too long(longer than 78, e.g.), python tries to break the usage string into parts at some proper positions and group them to multiple lines, then join the parts with space and assert it equal with original usage string. The regular expression used to break the usage string into parts is: metavar="[LIB,]FBNAME" seems quite reasonable and usable, in the case that one want to define an option who has tow values and the first is optional. So I suggest '[]' should be allowed in metavar, and the _format_usage() needs fixed. Here is a patch that fixes by changing the way breaking the usage string to parts and remove joining the parts and assert it equal to original usage string. Now the usage string is broken into intact each action of group usage strings. I think this breaking granularity is enough. |
I agree this is a bug. The patch needs to add unit tests that make sure metavars with [] work as expected. |
Attached the unit test. Here is the simpler script to product the bug: ------------------------ import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument ('--a', metavar='a'*76)
parser.add_argument ('--b', metavar="[innerpart]outerpart")
parser.add_argument ('c', metavar='c'*76)
parser.add_argument ('d', metavar="[innerpart2]outerpart2")
args = parser.parse_args() python thefile.py --help |
Sorry, got typo in last unit test. |
Tidied up the unit test. Mixed with arguments without metavar. |
Attached the preliminary fix and the unit test for this ticket. |
If the arg_parts are passed through the same cleanup as the 'text' (and empty strings removed), then
In that case there would be no need to return both (text, arg_parts). Parenthesis in the metavar could also create the problem addressed in this thread, except as noted in http://bugs.python.org/issue18349 that 'text' cleanup removes them. nargs='*' or '+' or integer is another way in which [] could be introduced into the metavar. |
I just filed a patch with http://bugs.python.org/issue10984 (argparse add_mutually_exclusive_group should accept existing arguments to register conflicts) that includes the latest patch from this issue. I tweaked it so _format_actions_usage only returns arg_parts. The block of _re. statements (# clean up separators for mutually exclusive groups) are in a nested function so it can be applied to each of the parts. In that issue I wrote a custom formatter that handles groups even if they share actions, or the action order does not match definition order. For that it is easier to work with the arg_parts as generated here rather than the whole usage line. |
paul j3, thanks for reviewing my patch and giving me credit in your patch for another ticket. Yeah, as you could see, the reason I return arg_parts and text is because the text still needs to undergo the cleanup process. You solved it by putting cleaning up in inner function. I am thinking whether it is best to do "assert ' '.join(opt_parts) == opt_usage" inside _format_actions_usage helper function. In that way, we can avoid returning the text. We can return only the arg_parts. Anyway, my patch still got some unused variables, notably part_regexp and inner. My bad. Let me check the code more deeply. See whether I can architect my patch in a better way. Maybe we can avoid building separate list inside _format_actions_usage. Beside of that, this bug is not introduced solely by bracket character. It needs another non-space character on the right side of it. This line is fine: This line will fail the assertion: |
Here's a patch that takes a different approach - rewrite _format_actions_usage() so it formats groups (and unattached actions) directly. It uses the same logic to determine when to format a group, but then it calls _format_group_usage() to format the group, without the error prone insert and cleanup business. And by keeping a list of the parts, it avoids the complications of parsing the text. The only cleanup regex removes () from single element groups. In the nested get_lines function, I added 'line and' to if line and line_len + 1 + len(part) > text_width: so it does not create a blank line before an extra long entry (e.g. 'c'*76). I'm using the _format_group_usage() and _format_just_actions_usage() in the bpo-10984 MultiGroupFormatter, just rearranging the logic in its _format_actions_usage() method. That patch could be rewritten to depend on this one. This patch also fixes http://bugs.python.org/issue18349, since the metavar is never parsed. |
Another example of code hitting this AssertionError. Here the problem was a space in the option argument, '--out '. http://stackoverflow.com/questions/23159845/python-argparse-assertionerror 'parser.add_argument('-o', '--out ', help='b', required = True)' That space would have cause problems later when trying access the 'args' attributes. But producing the error during the help formatting didn't help. |
It doesn't seem to be the exact same problem, but still this very simple example with parentheses in metavar fails to format correctly: import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputfiles", metavar = 'input_file(s)', nargs = "+", help = 'one or more input files')
args = parser.parse_args() --> usage: -m [-h] input_files) [input_file(s ...] positional arguments: optional arguments: with the two occurences of input_file(s) being formatted wrong, but differently. |
The patch with a major rewrite of '_format_actions_usage' handles this usage problem correctly:
The error is the result of usage group formatter trying to remove excess
|
Same AssertionError is also caused by having certain "choices". Python 2.7.10 global_options.add_argument('--field-sep', choices=[',',';','|','\t'], required=True, help='Field separator that separates columns in a row.') Removing required=True or removing the tab (\t) from the options both work around this usage formatter issue for me. I know this is an old issue but figured I would add another repro case to help whoever might work on this. |
Any changes here including the latest pull request might conflict with http://bugs.python.org/issue29553 Argparser does not display closing parentheses in nested mutex groups If someone uses nested mutually exclusive groups (which I don't think they should, but anyways ...), the usage formatter gets confused by the nested brackets, and weeds out the wrong one(s). That issue hasn't been settle yet; my feeling is that fixing this assertion error properly is more important. |
May I ask, how to assign reviewers for CPython pull requests? #1826 has been sitting there for 10 days and the only comment was from a bot. |
Thanks for the PR, and your patience! The change has now been merged for all active 3.x versions. It turns out the 2.7 argparse code is still close enough to the 3.x code for the automated backport to work, so the CI for that is currently running. |
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:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: