Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7688471
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T19:55:42+00:00 2026-05-31T19:55:42+00:00

Example of the problem If I have a list of valid option strings which

  • 0

Example of the problem

If I have a list of valid option strings which is shared between several arguments, the list is written in multiple places in the help string. Making it harder to read:

def main():
    elements = ['a', 'b', 'c', 'd', 'e', 'f']

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-i',
        nargs='*',
        choices=elements,
        default=elements,
        help='Space separated list of case sensitive element names.')
    parser.add_argument(
        '-e',
        nargs='*',
        choices=elements,
        default=[],
        help='Space separated list of case sensitive element names to '
        'exclude from processing')

    parser.parse_args()

When running the above function with the command line argument --help it shows:

usage: arguments.py [-h] [-i [{a,b,c,d,e,f} [{a,b,c,d,e,f} ...]]]
                    [-e [{a,b,c,d,e,f} [{a,b,c,d,e,f} ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -i [{a,b,c,d,e,f} [{a,b,c,d,e,f} ...]]
                        Space separated list of case sensitive element names.
  -e [{a,b,c,d,e,f} [{a,b,c,d,e,f} ...]]
                        Space separated list of case sensitive element names
                        to exclude from processing

What would be nice

It would be nice if one could define an option list name, and in the help output write the option list name in multiple places and define it last of all. In theory it would work like this:

def main_optionlist():
    elements = ['a', 'b', 'c', 'd', 'e', 'f']

    # Two instances of OptionList are equal if and only if they
    # have the same name (ALFA in this case)

    ol = OptionList('ALFA', elements)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-i',
        nargs='*',
        choices=ol,
        default=ol,
        help='Space separated list of case sensitive element names.')
    parser.add_argument(
        '-e',
        nargs='*',
        choices=ol,
        default=[],
        help='Space separated list of case sensitive element names to '
        'exclude from processing')

    parser.parse_args()

And when running the above function with the command line argument --help it would show something similar to:

usage: arguments.py [-h] [-i [ALFA [ALFA ...]]]
                    [-e [ALFA [ALFA ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -i [ALFA [ALFA ...]]
                        Space separated list of case sensitive element names.
  -e [ALFA [ALFA ...]]
                        Space separated list of case sensitive element names
                        to exclude from processing
sets in optional arguments:
  ALFA                  {a,b,c,d,e,f}

Question

I need to:

  • Replace the {‘l’, ‘i’, ‘s’, ‘t’, ‘s’} shown with the option name, in the optional arguments.
  • At the end of the help text show a section explaining which elements each option name consists of.

So I ask:

  1. Is this possible using argparse?
  2. Which classes would I have to inherit from and which methods would I need to override?

I have tried looking at the source for argparse, but as this modification feels pretty advanced I don´t know how to get going.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T19:55:43+00:00Added an answer on May 31, 2026 at 7:55 pm

    A completely generic solution as per request by the now deleted bounty-donator and in contrast to the other answers:

    import argparse
    from operator import itemgetter
    
    class OptionListGroup(object):
      class GroupAction(object):
        def __init__(self, left, right):
          self.help = right
          self.option_strings = [left]
          self.nargs = 0
    
      def __init__(self, lists):
        self.description = None
        self.title = "referenced sets"
        self._group_actions = [self.GroupAction(name, self.format_list(lst))
                               for name, lst in sorted(lists)]
    
      def format_list(self, lst):
        return '{%s}' % ', '.join(map(str, lst))
    
    class MyArgParser(argparse.ArgumentParser):
      def __init__(self, *args, **kwargs):
        self._option_lists = {}
        super(MyArgParser, self).__init__(*args, **kwargs)
    
      def parse_args(self, *args, **kw):
        self._action_groups.append(OptionListGroup(self._option_lists.values()))
        return super(MyArgParser, self).parse_args(*args, **kw)
    
      def add_option_list(self, name, lst):
        if name in map(itemgetter(0), self._option_lists.values()):
          raise ValueError, "Name already existing"
        self._option_lists[id(lst)] = (name, lst)
    
      def add_argument(self, *args, **kw):
        name_list = self._option_lists.get(id(kw.get('choices')))
        if name_list:
          kw['metavar'] = name_list[0]
        return super(MyArgParser, self).add_argument(*args, **kw)
    

    Example usage:

    alfa = ['a', 'b', 'c', 'd', 'e', 'f']
    num = [1, 2, 3]
    
    parser = MyArgParser()
    
    parser.add_option_list('ALFA', alfa)
    parser.add_option_list('NUM', num)
    
    parser.add_argument(
      '-a',
      nargs='*',
      choices=alfa,
      default=alfa,
      help='Characters (defaults to include all)')
    
    parser.add_argument(
      '-e',
      nargs='*',
      choices=num,
      default=[],
      help='Digits (defaults to exclude all)')
    
    parser.parse_args()
    

    Help output:

    usage: argparse-optionlist.py [-h] [-a [ALFA [ALFA ...]]]
                                  [-e [NUM [NUM ...]]]
    
    optional arguments:
      -h, --help            show this help message and exit
      -a [ALFA [ALFA ...]]  Characters (defaults to include all)
      -e [NUM [NUM ...]]    Digits (defaults to exclude all)
    
    referenced sets:
      ALFA                  {a, b, c, d, e, f}
      NUM                   {1, 2, 3}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Java - Regex problem I have list of URLs of types: http://www.example.com/pk/etc
i will give an example of the problem i have. My XML is like
i have problem use link_to_remote link_to_remote document example say link_to_remote Delete this post, :update
i have problem using LIKE structure in DB2 : for example: select * from
An application specific example to illustrate my immediate problem: I have a metadata provider
I have a problem with the Create View in the SimpleRepository example in Subsonic
I have a problem. I wrote example code and I want to build it
i'm download DrillDownApp example project from iPhoneSDKArticles i have a problem when i'm try
I have a problem with internet explorer 6 and 7, please look this example
Here's the problem: I have a list of items on a page, each with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.