Josh Rosenberg <shadowranger+pyt...@gmail.com> added the comment:

That's a *really* niche use case; you want to store everything to a common 
destination list, in order, but distinguish which switch added each one? I 
don't know of any programs that use such a design outside of Python (and 
therefore, it seems unlikely there would be enough demand from argparse users 
to justify the development, maintenance, and complexity cost of adding it).

argparse does support defining custom Actions, so it's wholly possible to add 
this sort of support for yourself if there isn't enough demand to add it to 
argparse itself. For example, a simple implementation would be:

class AppendWithSwitchAction(argparse.Action):
    def __init__(self, option_strings, dest, *args, **kwargs):
        super().__init__(option_strings, dest, *args, **kwargs)
        # Map all possible switches to the final switch provided
        # so we store a consistent switch name
        self.option_map = dict.fromkeys(option_strings, option_strings[-1])

    def __call__(self, parser, namespace, values, option_string=None):
        option = self.option_map.get(option_string)
        try:
            getattr(namespace, self.dest).append((option, value))
        except AttributeError:
            setattr(namespace, self.dest, [(option, value)])

then use it with:

parser.add_argument('-p', '--preload', help='preload asset', 
action=AppendWithSwitchAction, metavar='NAMESPACE')

parser.add_argument('-f', '--file', help='preload file', 
action=AppendWithSwitchAction, metavar='FILE', dest='preload')

All that does is append ('--preload', argument) or ('--file', argument) instead 
of just appending the argument, so you can distinguish one from the other (for 
switch, arg in args.preload:, then test if switch=='--preload' or '--file'). 
It's bare bones (the actual class underlying the 'append' action ensures nargs 
isn't 0, and that if const is provided, nargs is '?'), but it would serve.

----------
nosy: +josh.r

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue34458>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to