Issue 18349: argparse usage should preserve () in metavars such as range(20) (original) (raw)
Created on 2013-07-03 06:16 by paul.j3, last changed 2022-04-11 14:57 by admin.
Messages (5)
Author: paul j3 (paul.j3) *
Date: 2013-07-03 06:16
As discussed in issue 16468, a metavar may be used to provide an alternative representation of a choices option. However if a metvar like 'range(20)' is used, usage formatter strips off the '()'.
>>> parser.add_argument('foo', type=int,
choices=range(20), metavar='range(0,20)')
>>> parser.format_usage()
# expect: 'usage: PROG [-h] range(0,20)\n'
# actual: 'usage: PROG [-h] range0,20\n'
This is done by a line in the help formater that removes excess mutually exclusive group notation:
HelpFormatter._format_actions_usage
...
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
A solution is to change this line to distinguish between a case like ' (...)' and 'range(...)'
text = _re.sub(r'( )\(([^|]*)\)', r'\1\2', text)
Author: paul j3 (paul.j3) *
Date: 2013-07-09 03:08
I just posted a patch to http://bugs.python.org/issue16468 that uses (and tests) this fix.
Author: paul j3 (paul.j3) *
Date: 2013-07-15 07:15
This issue should also preserve a metavar like: '(one)two', i.e. '(' at the start.
In http://bugs.python.org/issue10984 these _re replacements are applied to individual action strings as well as the whole usage line. So if () are to be removed from '[-h] (-y)', they should also be removed from '(-y)'.
Author: paul j3 (paul.j3) *
Date: 2013-07-16 20:34
I just submitted at patch to http://bugs.python.org/issue11874 that takes care of this issue as well.
I rewrote _format_actions_usage() so it formats the parts directly, so there is no need cleanup or parse the full text string.
Author: Irit Katriel (iritkatriel) *
Date: 2021-12-10 15:48
Reproduced on 3.11:
import argparse parser = argparse.ArgumentParser() parser.add_argument('foo', type=int, choices=range(20), metavar='range(0,20)') _StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=<class 'int'>, choices=range(0, 20), help=None, metavar='range(0,20)') parser.format_usage() 'usage: [-h] range0,20\n'
History
Date
User
Action
Args
2022-04-11 14:57:47
admin
set
github: 62549
2021-12-10 15:48:45
iritkatriel
set
nosy: + iritkatriel
messages: +
versions: + Python 3.9, Python 3.10, Python 3.11, - Python 3.4
2013-07-16 20:34:49
paul.j3
set
messages: +
2013-07-15 07:15:36
paul.j3
set
messages: +
2013-07-09 03:08:49
paul.j3
set
messages: +
2013-07-03 06:19:39
paul.j3
set
type: behavior
components: + Library (Lib)
versions: + Python 3.4
2013-07-03 06:16:51
paul.j3
create