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 8537183
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T10:50:19+00:00 2026-06-11T10:50:19+00:00

Python optparse normally allows the user to specify an option more than once and

  • 0

Python optparse normally allows the user to specify an option more than once and silently ignores all occurrences of the option but the last one. For example, if the action of option --foo is store and the action of option --flag is store_const, store_true or store_false, the following commands will be equivalent:

my-command --foo=bar --foo=another --flag --foo=last --flag
my-command --flag --foo=last

(Update: argparse does just the same thing by default.)

Now, I have a lot of options, and specifying any of them more than once doesn’t make sense. If a user specifies the same option more than once I’d like to warn them about the possible error.

What is the most elegant way to detect options that were specified multiple times? Note that the same option can have a short form, a long form and abbreviated long forms (so that -f, --foobar, --foob and --foo are all the same option). It would be even better if it was possible to detect the case when multiple options that have the same destination were specified simultaneously, so that a warning can be given if a user specifies both --quiet and --verbose while both options store a value into the same destination and effectively override each other.

Update: To be more user-friendly, the warning should refer to the exact option names as used on the command line. Using append actions instead of store is possible, but when we detect a conflict, we cannot say which options caused it (was it -q and --verbose or --quiet --quiet?).

Unfortunately I’m stuck with optparse and cannot use argparse because I have to support Python 2.6.

P. S. If you know of a solution that works only with argparse, please post it, too. While I try to minimize the number of external dependencies, using argparse under Python 2.6 is still an option.

  • 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-06-11T10:50:21+00:00Added an answer on June 11, 2026 at 10:50 am

    I think the correct way would be to “define your action” in some way.

    For example, you could use the action callback and implement a function that implement your desired behaviour.
    You could write a function that first checks if the destination was already filled, if it is filled then it stores the overlapping options into a list.
    When the parsing is finished you should check if these lists are empty, and if they are not raise the appropriate exception.

    Another way of doing this could be to define your own action. You can have a look here

    A small example that uses the callback:

    import sys
    import functools
    from optparse import OptionParser
    
    
    bad_option = 'BAD OPTION'
    
    def store(option, opt, value, parser, dest, val):
        """Set option's destination *dest* to *val*  if there are no conflicting options."""
        list_name = dest + '_options_list'
        try:
            # if this option is a conflict, save its name and set the value to bad_option
            getattr(parser.values, list_name).append(opt)
            setattr(parser.values, dest, bad_option)
        except AttributeError:
            # no conflicts, set the option value and add the options list
            setattr(parser.values, dest, val)
            setattr(parser.values, list_name, [opt])
    
    store_true = functools.partial(store, val=True)
    store_false = functools.partial(store, val=False)
    
    
    parser = OptionParser()
    parser.add_option('-v', '--verbose',
                      action='callback', callback=store_true,
                      help='Increase output verbosity',
                      callback_kwargs={'dest': 'verbose'})
    
    parser.add_option('-q', '--quiet',
                      action='callback', callback=store_false,
                      help='Decrease output verbosity',
                      callback_kwargs={'dest': 'verbose'})
    
    opts, args = parser.parse_args()
    
    # detects all conflicting options for all destinations
    found = False
    for dest in ('verbose',):
        if getattr(opts, dest) == bad_option:
            conflicting_opts = ', '.join(getattr(opts, dest + '_options_list'))
            print('Conflicting options %s for destination %s'
                  % (conflicting_opts, dest))
            found = True
    
    if found:
        parser.print_usage()
        sys.exit(2)
    

    And the output:

    $ python testing_optparse.py -v -q
    Conflicting options -v, -q for destination verbose
    Usage: prova_optparse.py [options]
    

    Probably it would be better to raise an OptionValueError when detecting conflicts, even though this would allow to get only couple of conflicting options. If you want to get all conflicting options you have to parse the remaining arguments( in parser.rargs).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When using optparse i want to get the whole string after an option, but
What's the functionality of the dry-run option in the optparse module of Python?
I'm currently learning on how to use the Python optparse module. I'm trying the
In python, I can construct my optparse instance such that it will automatically filter
(Python) Given two numbers A and B. I need to find all nested groups
Python is on version 2.7.3, but when i try to upgrade python through pip
Python allows aliasing of imports, through ...as <ALIAS> clauses in the import statement, like
Python optparse works very good when script usage is something like this %prog [options]
Using python's optparse module I would like to add extra example lines below the
Python and django newbie question, here is code: class Client(User) #some fields client=Client() client.save()

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.