argparse: fix inconsistency in `add_argument()` API when using positional argument with `dest=` parameter
Open
Nobody has claimed this yet.
type-feature
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
Feature or enhancement
Proposal:
Current behaviour is ugly and inconsistent between options and positional arguments:
parser.add_argument("--option-foo", dest="my_foo_option_var")
parser.add_argument(metavar="BAR_ARG", dest="my_bar_arg_var")
# or even worse
parser.add_argument("my_bar_arg_var", metavar="BAR_ARG")
Proposed change streamlines the library API
parser.add_argument("--option-foo", dest="my_foo_option_var")
parser.add_argument("BAR_ARG", dest="my_bar_arg_var")
I think a small patch could fix this without breaking any existing code.
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -1423,7 +1423,7 @@
# =======================
def add_argument(self, *args, **kwargs):
"""
- add_argument(dest, ..., name=value, ...)
+ add_argument(arg, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
@@ -1433,7 +1433,11 @@
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
- raise ValueError('dest supplied twice for positional argument')
+ if 'metavar' not in kwargs:
+ kwargs['metavar'] = args[0]
+ else:
+ raise ValueError('`arg` supplied with both `dest` and `metavar` for positional argument')
+ args = (kwargs.pop('dest'), )
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in Lib/argparse.py at the add_argument entry point and review the current positional-argument handling against the proposal. Check the existing argparse tests and confirm that the new positional dest and metavar behavior works while existing forms remain compatible.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- cli
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100