[issue29030] argparse: choices override metavar

paul j3 report at bugs.python.org
Fri Jan 6 16:44:59 EST 2017


paul j3 added the comment:

Here's the method in HelpFormatter that creates the metavar:

    def _metavar_formatter(self, action, default_metavar):
        if action.metavar is not None:
            result = action.metavar
        elif action.choices is not None:
            choice_strs = [str(choice) for choice in action.choices]
            result = '{%s}' % ','.join(choice_strs)
        else:
            result = default_metavar

        def format(tuple_size):
            if isinstance(result, tuple):
                return result
            else:
                return (result, ) * tuple_size
        return format

So in order of priority it uses: 

    the explicit metavar parameter
    formatted choices
    a default metavar (normally derived from the dest)

The MetavarTypeHelpFormatter subclass changes how that default is derived.  In the same spirit, you could write your own Formatter subclass that changes the above method, and its priority order.

In your example, the use of choices in the 'usage' like looks good to me.  I agree that its use in the 'help' line does not look so good.  But don't forget that for your end user, the positional 'dest' (or name) has no value.  Only you as the programmer sees and uses it.

This is one of many implementation details that could be included in the argparse docs.  But for some users those docs are already too complex.  The existing docs are not a formal module reference.

----------
nosy: +paul.j3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue29030>
_______________________________________


More information about the Python-bugs-list mailing list