This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author josh.r
Recipients josh.r, porton
Date 2018-08-22.14:57:21
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1534949841.16.0.56676864532.issue34458@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2018-08-22 14:57:21josh.rsetrecipients: + josh.r, porton
2018-08-22 14:57:21josh.rsetmessageid: <1534949841.16.0.56676864532.issue34458@psf.upfronthosting.co.za>
2018-08-22 14:57:21josh.rlinkissue34458 messages
2018-08-22 14:57:21josh.rcreate