Commit Graph

125 Commits

Author SHA1 Message Date
Ali Hamdan de1428f8c2
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
2024-05-07 09:28:51 +02:00
Amethyst Reese 4a63098032
gh-116159: argparse: performance improvement parsing large number of options (#116162)
When parsing positional vs optional arguments, the use of min with a
list comprehension inside of a loop results in quadratic time based
on the number of optional arguments given. When combined with use of
prefix based argument files and a large number of optional flags, this
can result in extremely slow parsing behavior.

This replaces the min call with a simple loop with a short circuit to
break at the next optional argument.

Co-authored-by: Zsolt Dollenstein <zsol.zsol@gmail.com>
2024-03-01 11:52:53 +01:00
Jérémie Detrey 6087315926
bpo-44865: Fix yet one missing translations in argparse (GH-27668) 2024-02-26 22:05:01 +00:00
Emmanuel Arias da382aaf52
gh-77956: Add the words 'default' and 'version' help text localizable (GH-12711)
Co-authored-by: paul.j3
Co-authored-by: Jérémie Detrey <jdetrey@users.noreply.github.com>
2024-02-26 19:20:39 +00:00
Daniel Mach 5f7df88821
gh-96310: Fix a traceback in argparse when all options in a mutually exclusive group are suppressed (GH-96311)
Reproducer depends on terminal size - the traceback occurs when there's
an option long enough so the usage line doesn't fit the terminal width.
Option order is also important for reproducibility.

Excluding empty groups (with all options suppressed) from inserts
fixes the problem.
2024-02-21 13:58:04 +00:00
Frank Dana b052fa381f
argparse: remove incoherent and redundant docstring for private method (GH-101591)
Signed-off-by: FeRD (Frank Dana) <ferdnyc@gmail.com>
2024-02-21 11:32:28 +00:00
Serhiy Storchaka e47ecbd042
gh-60346: Improve handling single-dash options in ArgumentParser.parse_known_args() (GH-114180) 2024-02-19 19:20:00 +02:00
Serhiy Storchaka bb57ffdb38
gh-83648: Support deprecation of options, arguments and subcommands in argparse (GH-114086) 2024-02-06 00:41:34 +02:00
Serhiy Storchaka 4aa4f0906d
gh-109475: Fix support of explicit option value "--" in argparse (GH-114814)
For example "--option=--".
2024-02-05 22:42:43 +02:00
Jokimax c4a2e8a2c5
gh-101599: argparse: simplify the option help string (GH-103372)
If the option with argument has short and long names,
output argument only once, after the long name:

   -o, --option ARG    description

instead of

   -o ARG, --option ARG    description
2024-02-02 22:13:00 +00:00
Alex Waygood bfe7e72522
gh-109653: Defer importing `warnings` in several modules (#110286) 2023-10-04 06:09:43 +01:00
Tian Gao 9efaff5fd3
gh-103558: Add coverage tests for argparse (#103570)
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
2023-06-05 00:14:00 -07:00
Nikita Sobolev 27a7d5e1cd
gh-92248: Deprecate `type`, `choices`, `metavar` parameters of `argparse.BooleanOptionalAction` (#103678)
Co-authored-by: Kirill <80244920+Eclips4@users.noreply.github.com>
Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
Co-authored-by: Oleg Iarygin <oleg@arhadthedev.net>
2023-05-19 16:44:43 +00:00
Burak Saler 01cc9c1ff7
gh-104273: Remove redundant len() calls in argparse function (#104274) 2023-05-07 19:43:50 -04:00
Oleg Iarygin 42f54d1f92
gh-101640: Make argparse _print_message catch any write error (#101802)
* In particular, don't exit when trying to print to stderr = None.
* Add tests

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
2023-05-06 18:53:48 -04:00
Yeojin Kim 9a478be1a4
gh-101979: argparse: fix a bug where parentheses in metavar argument of add_argument() were dropped (#102318) 2023-03-05 06:54:33 -08:00
Hai Shi e02cc6d42a
gh-80448: argparse: Fix IndexError on store_true action (#15656)
Co-authored-by: Rémi Lapeyre <remi.lapeyre@henki.fr>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2022-11-11 17:51:38 -08:00
Jonathon Reinhart 30878a7735
argparse: Remove unused name variable when handling ArgumentTypeError (#96549)
This removes the unused `name` variable in the block where `ArgumentTypeError` is handled.

`ArgumentTypeError` errors are handled by showing just the string of the exception; unlike `ValueError`, the name (`__name__`) of the function is not included in the error message.

Fixes #96548
2022-09-05 14:32:23 -07:00
Harry ad7340e8c5
gh-92445 Improve interaction between nargs="*" and choices() (GH-92565) 2022-08-25 06:18:38 -05:00
Inada Naoki 9877f4c624
gh-85308: argparse: Use filesystem encoding for arguments file (GH-93277) 2022-06-23 12:09:57 +09:00
DjMorgul b885b8f4be
Allow translating argument error messages (#17169) 2022-05-05 00:32:49 -05:00
Toshio Kuratomi 20490d5018
gh-88753: Make BooleanOptionalAction's addition of default to help more similar to other actions (#27808)
Help for other actions omit the default value if default is SUPPRESS or
already contains the special format string '%(default)'.  Add those
special cases to BooleanOptionalAction's help formatting too.

Fixes https://bugs.python.org/issue44587 so that default=SUPPRESS is not
emitted.

Fixes https://bugs.python.org/issue38956 as this code will detect
whether '%(default)s' has already been specified in the help string.

Signed-off-by: Micky Yun Chan (michiboo): <chanmickyyun@gmail.com>
Co-authored-by: Micky Yun Chan <michan@redhat.com>
2022-05-03 18:38:18 +02:00
Antony Lee ad5e8520f3
bpo-39716: Raise on conflicting subparser names. (GH-18605)
Raise an ArgumentError when the same subparser name is added twice to an
ArgumentParser.  This is consistent with the (default) behavior when the
same option string is added twice to an ArgumentParser.

(Support for `conflict_handler="resolve"` could be considered as a
followup feature, although real use cases seem even rarer than
"resolve"ing option-strings.)

Automerge-Triggered-By: GH:rhettinger
2022-04-30 23:04:50 -07:00
Abhigyan Bose 4ed3900041
gh-91832: Add 'required' attr to argparse.Action repr (GH-91841)
# Adding 'required' to names in Lib.argparse.Action

gh-91832: 
Added 'required' to the list `names` in `Lib.argparse.Action`. 
Changed constant strings that test the Action object.

Automerge-Triggered-By: GH:merwok
2022-04-28 07:50:27 -07:00
Victor Stinner c77953b23e
Revert "gh-85567: Register a cleanup function to close files for FileType objects in argparse (#32257)" (#91771)
This reverts commit 328dbc051f.
2022-04-21 03:10:51 +02:00
achhina 328dbc051f
gh-85567: Register a cleanup function to close files for FileType objects in argparse (#32257)
* bpo-41395: Register a cleanup function to close files for FileType objects in argparse

* Added import as top level import, and renamed file as fh.
2022-04-17 22:53:37 -03:00
MojoVampire eafec26ae5
bpo-14156: Make argparse.FileType work correctly for binary file modes when argument is '-' (GH-13165)
Also made modes containing 'a' or 'x' act the same as a mode containing 'w' when argument is '-'
(so 'a'/'x' return sys.stdout like 'w', and 'ab'/'xb' return sys.stdout.buffer like 'wb').
2022-03-06 13:49:42 +02:00
Kumar Aditya 45f5f52601
bpo-46510: update Python2-style exception handling in argparse (GH-30881) 2022-01-25 15:34:03 +00:00
Felix Fontein 9e87c0e03f
bpo-46080: fix argparse help generation exception in edge case (GH-30111)
Fix an uncaught exception during help text generation when
argparse.BooleanOptionalAction is used with default=argparse.SUPPRESS
and help is specified.
2022-01-21 00:48:48 +02:00
Jade Lovelace 8e75c6b49b
argparse docs: prog default is the basename of argv[0] (GH-30298) 2022-01-02 12:16:25 -08:00
Irit Katriel 30322c497e
bpo-22047: [argparse] deprecate nested argument groups and mutually exclusive groups (GH-30098) 2021-12-16 15:31:08 +00:00
Irit Katriel 86de99588d
bpo-26952: [argparse] clearer error when formatting an empty mutually… (GH-30099) 2021-12-15 10:08:26 +00:00
Raymond Hettinger 807f839bbf
bpo-45235: Revert an argparse bugfix that caused a regression (GH-29525)
* Revert "bpo-45235: Fix argparse overrides namespace with subparser defaults (GH-28420) (GH-28443)"

This reverts commit a18d52269a.
2021-11-11 21:53:23 -06:00
andrei kulakov 6fafc25aea
bpo-24444: fix an error in argparse help when help for an option is blank (GH-28050) 2021-10-13 18:31:51 +02:00
Adam Schwalm a6e8db5e8e
bpo-45235: Fix argparse overrides namespace with subparser defaults (GH-28420) 2021-09-17 23:20:31 -05:00
Maximilian Hils 1512bc21d6
bpo-38956: don't print BooleanOptionalAction's default twice (GH-27672)
Co-authored-by: Micky Yun Chan <michan@redhat.com>
2021-08-16 23:42:21 +02:00
Jack DeVries 0ad173249d
bpo-37880: for argparse add_argument with action='store_const', const now defaults to None. (GH-26707) 2021-07-31 17:27:55 +01:00
Anthony Sottile 17575f73ce
bpo-29298: Fix crash with required subparsers without dest (GH-3680)
Automerge-Triggered-By: GH:encukou
2021-07-23 05:49:04 -07:00
Raymond Hettinger 41b223d29c
bpo-9694: Fix misleading phrase "optional arguments" (GH-23858) 2020-12-23 09:40:56 -08:00
Rémi Lapeyre b084d1b97e
bpo-40862: Raise TypeError when const is given to argparse.BooleanOptionalAction (GH-20623) 2020-06-05 15:00:42 -07:00
Raymond Hettinger 9681953c99
bpo-39058: Preserve attribute order in argparse Namespace reprs. (GH-17621) 2020-05-17 18:53:01 -07:00
Kyle Meyer 8edfc47bae
bpo-39546: argparse: Honor allow_abbrev=False for specified prefix_chars (GH-18337)
When `allow_abbrev` was first added, disabling the abbreviation of
long options broke the grouping of short flags ([bpo-26967](https://bugs.python.org/issue26967)).  As a fix,
b1e4d1b603 (contained in v3.8) ignores `allow_abbrev=False` for a
given argument string if the string does _not_ start with "--"
(i.e. it doesn't look like a long option).

This fix, however, doesn't take into account that long options can
start with alternative characters specified via `prefix_chars`,
introducing a regression: `allow_abbrev=False` has no effect on long
options that start with an alternative prefix character.

The most minimal fix would be to replace the "starts with --" check
with a "starts with two prefix_chars characters".  But
`_get_option_tuples` already distinguishes between long and short
options, so let's instead piggyback off of that check by moving the
`allow_abbrev` condition into `_get_option_tuples`.





https://bugs.python.org/issue39546
2020-02-18 01:48:57 -08:00
Raymond Hettinger b4e5eeac26
Defer import of shutil which only needed for help and usage (GH-17334) 2019-11-21 22:51:45 -08:00
Federico Bond be5c79e033 bpo-38821: Fix crash in argparse when using gettext (GH-17192) 2019-11-20 15:29:29 +02:00
Brandt Bucher a0ed99bca8 bpo-38438: Simplify argparse "star nargs" usage. (GH-17106) 2019-11-11 12:47:48 -08:00
Rémi Lapeyre 6a517c6749 bpo-8538: Add support for boolean actions to argparse (GH-11478)
Co-Authored-By: remilapeyre <remi.lapeyre@henki.fr>
2019-09-13 11:17:43 +01:00
Jakub Kulík 42671aea2d bpo-37785: Fix xgettext warning in argparse (GH-15161) 2019-09-13 11:25:32 +02:00
Hai Shi f545638b57 bpo-9938: Add optional keyword argument exit_on_error to argparse.ArgumentParser (GH-15362)
Co-Authored-by: Xuanji Li <xuanji@gmail.com>


https://bugs.python.org/issue9938



Automerge-Triggered-By: @matrixise
2019-09-12 03:56:05 -07:00
Raymond Hettinger 496058f599
Steven Bethard designated a new maintainer for argparse (GH-15605) 2019-08-29 21:04:37 -07:00
Flavian Hautbois da27d9b9dc bpo-29553: Fix ArgumentParser.format_usage() for mutually exclusive groups (GH-14976)
Co-authored-by: Andrew Nester <andrew.nester.dev@gmail.com>
2019-08-25 22:06:45 +03:00