]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-62090: Simplify argparse usage formatting (GH-105039)
authorAli Hamdan <ali.hamdan.dev@gmail.com>
Tue, 7 May 2024 07:28:51 +0000 (10:28 +0300)
committerGitHub <noreply@github.com>
Tue, 7 May 2024 07:28:51 +0000 (09:28 +0200)
commitde1428f8c234a8731ced99cbfe5cd6c5c719e31d
treeee30a62229c516a98e5addd041a0f5b83bc7718a
parent49258efada0cb0fc58ccffc018ff310b8f7f4570
gh-62090: Simplify argparse usage formatting (GH-105039)

Rationale
=========

argparse performs a complex formatting of the usage for argument grouping
and for line wrapping to fit the terminal width. This formatting has been
a constant source of bugs for at least 10 years (see linked issues below)
where defensive assertion errors are triggered or brackets and paranthesis
are not properly handeled.

Problem
=======

The current implementation of argparse usage formatting relies on regular
expressions to group arguments usage only to separate them again later
with another set of regular expressions. This is a complex and error prone
approach that caused all the issues linked below. Special casing certain
argument formats has not solved the problem. The following are some of
the most common issues:
- empty `metavar`
- mutually exclusive groups with `SUPPRESS`ed arguments
- metavars with whitespace
- metavars with brackets or paranthesis

Solution
========

The following two comments summarize the solution:
- https://github.com/python/cpython/issues/82091#issuecomment-1093832187
- https://github.com/python/cpython/issues/77048#issuecomment-1093776995

Mainly, the solution is to rewrite the usage formatting to avoid the
group-then-separate approach. Instead, the usage parts are kept separate
and only joined together at the end. This allows for a much simpler
implementation that is easier to understand and maintain. It avoids the
regular expressions approach and fixes the corresponding issues.

This closes the following GitHub issues:
-  #62090
-  #62549
-  #77048
-  #82091
-  #89743
-  #96310
-  #98666

These PRs become obsolete:
-  #15372
-  #96311
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2023-05-28-11-25-18.gh-issue-62090.opAhDn.rst [new file with mode: 0644]