Issue 28219: Is order of argparse --help output officially defined? (original) (raw)

Sometimes we want to control the order of arguments printed by an argparse defined cli. In practice, arguments are printed in the order in which they are added via add_argument(), but I don't think this is documented and thus should be considered an implementation detail. It should be possible to enforce an order by the use of a formatter_class, but you'd probably need some extra metadata on arguments to do this, so it's not completely obvious how to write such a formatter class.

Instead, I propose to document and officially support that the order of add_argument() calls defines the order in which arguments are printed via --help.

The display of the Action help lines is determined by the parser.format_help function

https://docs.python.org/3/library/argparse.html#printing-help

This function creates a Formatter, and then loads it with a 'stack' of sections. Sections are displayed in that order:

    # usage (with self._actions)
    # description
    # groups

    for action_group in self._action_groups:
        formatter.start_section(action_group.title)
        formatter.add_text(action_group.description)
        formatter.add_arguments(action_group._group_actions)
        formatter.end_section()

parser._actions is the list of Actions (arguments) in the order in which they were created.

Usage displays them, first the optionals, then the positionals. Some Stackoverflow posters have asked about changing that order. That requires customizing the usage formatter method.

Help is displayed by group, and with in that by creation order. There are 2 default groups, positionals and optionals. User defined groups follow. https://docs.python.org/3/library/argparse.html#argument-groups

Probably the simplest way to write help lines in a different order is to write a custom parser.format_help method.

Subclassing HelpFormatter is the 'accepted' way of customizing the help. The provided subclasses work by modifying just one or two methods. But given how a formatter works it is much easier to change the order while 'loading' the formatter rather than after it has been created.

I don't see the point to etching this behavior into the documentation. It's the default behavior, and relatively obvious from a few examples. If we were to add some sort of customization then we'd need to elaborate. This documentation is more of a how-to document than a formal description of the module. This is just one of the many details that are determined by the code rather the documentation.

But feel free to suggest a formal change to the documentation.