Python argparse AssertionError

There is an extra space after --out in the code. Change:

parser.add_argument('-o', '--out ', help='b', required = True)

to:

parser.add_argument('-o', '--out', help='b', required = True)

The underlying cause of the problem is an assert check within the Python code that only occurs when Python attempts to break the help text into multiple lines because it is too long. After breaking the text into a list, the Python code joins it back together and compares it to the original to ensure that it is correct. However, the code that breaks the text apart drops the adjoining spaces resulting in a miscompare.

I added prints to the code (argparse.py, Python 2.7):

# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
    # break usage into wrappable parts
    part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
    opt_usage = format(optionals, groups)
    pos_usage = format(positionals, groups)
    opt_parts = _re.findall(part_regexp, opt_usage)
    pos_parts = _re.findall(part_regexp, pos_usage)
    print ' '.join(opt_parts)
    print opt_usage
    assert ' '.join(opt_parts) == opt_usage

And the results:

[-h] -f FIN -o OUT -t TRANS
[-h] -f FIN -o OUT  -t TRANS
Traceback (most recent call last):
  File "blah.py", line 9, in <module>
    args = parser.parse_args()

Note the extra space after OUT.

This explains all of the observed behavior:

  • Must be long enough to trigger the wrapping behavior.
  • Deleting the --trans argument moved --out to the end negating the behavior.
  • Deleting the --out argument negateted the behvaior.

The problem is not the extra -h that you've added. Look at the error and the -o argument:

assert ' '.join(opt_parts) == opt_usage

it's joining the whitespace in '--out '. If you remove it, everything should work fine.


I came here with the exact same problem/error, but without having any extra spaces after --out. My problem was that metavar was set to an empty string (metavar=''). Changing that resolved the issue.