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 monkeyman79
Recipients monkeyman79, paul.j3, r.david.murray, v+python
Date 2021-01-26.00:30:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1611621011.84.0.528186355507.issue42973@roundup.psfhosted.org>
In-reply-to
Content
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'.
History
Date User Action Args
2021-01-26 00:30:11monkeyman79setrecipients: + monkeyman79, v+python, r.david.murray, paul.j3
2021-01-26 00:30:11monkeyman79setmessageid: <1611621011.84.0.528186355507.issue42973@roundup.psfhosted.org>
2021-01-26 00:30:11monkeyman79linkissue42973 messages
2021-01-26 00:30:11monkeyman79create