Tadek Kijkowski <tkijkow...@gmail.com> added the comment:
This is, I think, smallest functional example for matching optional parameters with positionals - fruits.py: import argparse DEFAULT_COLOR="plain" class AddFruitAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): for fruit in values: namespace.fruits.append({'name': fruit, 'color': namespace.color}) namespace.color = DEFAULT_COLOR def show_fruits(fruits): for fruit in fruits: print(f"{fruit['color']} {fruit['name']}") parser = argparse.ArgumentParser(greedy=True) parser.add_argument('--color', default=DEFAULT_COLOR) parser.add_argument('fruits', nargs='*', action=AddFruitAction, default=[]) args = parser.parse_args() show_fruits(args.fruits) It starts with 'namespace.color' set to 'DEFAULT_COLOR' - 'default=DEFAULT_COLOR' takes care of that, and with 'namespace.fruits' set to empty list - via 'default=[]'. For each group of positional command-line arguments, AddFruitAction is called with one or more fruit names in 'value'. The method iterates over them adding series of dicts to the 'fruits' list. The 'namespace.color' is immediately reset to default value, because we want the 'color' to apply to one following 'fruit'. If we wanted the 'color' to apply to all following 'fruits' the action class could just leave it alone. After parsing is done, we get our namespace assigned to args, with list of color + fruit name pairs in 'args.fruits'. ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue42973> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com