[docs] [issue9694] argparse required arguments displayed under "optional arguments"

paul j3 report at bugs.python.org
Thu Feb 13 04:22:54 CET 2014

paul j3 added the comment:

As Steven pointed out, the existing `add_argument_group` mechanism can be used to group required arguments.  For example

    ------------------------- temp.py --------------------------
    parser = argparse.ArgumentParser(description = 'Do something')
    group1 = parser.add_argument_group('required arguments')
    group1.add_argument('--reqarg', '-r', required=True)
    usage: ipython [-h] --reqarg REQARG [--optarg OPTARG] foo
    Do something
    positional arguments:
    optional arguments:
      -h, --help            show this help message and exit
      --optarg OPTARG, -o OPTARG
    required arguments:
      --reqarg REQARG, -r REQARG

Positional 'foo' can also be put in the 'required' group:

    required arguments:
      --reqarg REQARG, -r REQARG

The distinction between 'positionals' and 'optionals' (or flagged) is essential to the parsing, but it is not necessary for Help Formatting.

I can imagine grouping arguments by 'required/not-required' properties.  It might be worth constructing an alternative HelpFormatter class that regroups the arguments in this way.  Subclassing the HelpFormatter is the established way of adding features to the help display.

The existing HelpFormatter flags 'required' arguments in the usage line with '[]'.  There it is has the added task of flagging Mutually Exclusive Groups in the same way.

It's worth keeping in mind that whether an argument is 'required' or not is determined in 2 different ways.  There is an optional 'required' flag (default False).  But this flag is not allowed for 'positionals'.  Instead with those 'argparse' looks at 'nargs' ('?*' are not required).

The 'required' attribute of an argument (Action) is ignored during 'parse_args' until the end.  At that time it makes an inventory of 'required' arguments that have not been seen, and potentially raises an error.  That testing was changed in a relatively recent patch, and produced an unintended change in whether 'subparsers' were required or not. (I could look up those issues in needed).

I'll think about creating the alternative HelpFormatter.


Python tracker <report at bugs.python.org>

More information about the docs mailing list