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

The Archive Base Latest Questions

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

This is slightly related to the topic covered in a question about allowing an

  • 0

This is slightly related to the topic covered in a question about allowing an argument to be specified multiple times.

I’d like to be able to specify an option multiple times like this:

 tool --foo 1 --foo 2 --foo 3

And also like this:

 tool a b c

I’d also like to support both at the same time:

 tool a b c --foo 1 --foo2 --foo 3

This works fine with:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo', nargs='*', action='append')
parser.add_argument('--foo', nargs='*', dest='foo', action='append')

The result list can be easily flattened out:

args = parser.parse_args('a b c --foo 1 --foo 2 --foo 3'.split())
args.foo = [el for elements in args.foo for el in elements]

yields:

>>> args
Namespace(foo=['a', 'b', 'c', '1', '2', '3'])

How do I add a default value in a way that the default is not being used as soon as one argument is specified by the user?

If adding just default=[['spam']] to one of the add_argument() calls, the default is always part of the result. I cannot get argparse to remove it by itself as soon as a user provides an argument herself.

I’m hoping that there’s a solution with what argparse already provides itself.

  • 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:45:33+00:00Added an answer on June 11, 2026 at 10:45 am

    I think this is a slightly more clean variation on the other answer (relying on the self.default attribute of custom actions):

    import argparse
    import sys
    
    class Extender(argparse.Action):
        def __call__(self,parser,namespace,values,option_strings=None):
            #Need None here incase `argparse.SUPPRESS` was supplied for `dest`
            dest = getattr(namespace,self.dest,None) 
            #print dest,self.default,values,option_strings
            if(not hasattr(dest,'extend') or dest == self.default):
                dest = []
                setattr(namespace,self.dest,dest)
                #if default isn't set to None, this method might be called
                # with the default as `values` for other arguements which
                # share this destination.
                parser.set_defaults(**{self.dest:None}) 
    
            try:
                dest.extend(values)
            except ValueError:
                dest.append(values)
    
            #another option:
            #if not isinstance(values,basestring):
            #    dest.extend(values)
            #else:
            #    dest.append(values) #It's a string.  Oops.
    
    def new_parser(args):
        parser = argparse.ArgumentParser()
        parser.add_argument('foo', nargs='*',action=Extender)
        parser.add_argument('--foo', nargs='*', dest='foo', action=Extender)
        parser.set_defaults(foo = [['spam']])
        return parser.parse_args(args.split())
    
    tests = {'a b c --foo 1 --foo 2 --foo 3':['a','b','c','1','2','3'],
             '':[['spam']],
             'a b c --foo 1 2 3':['a','b','c','1','2','3'],
             '--foo 1':['1'],
             'a':['a']}
    
    for s,r in tests.items():
        print ( "parsing: {0}".format(s) )
        args = new_parser(s)
        if(args.foo != r):
            print ("ERROR")
            print (args.foo)
            print (r)
            sys.exit(1)
        print ( args )
        print ('*'*80)
    

    Also note that I’ve used parser.set_defaults(...) to set the default for the foo attribute.

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

Sidebar

Related Questions

Slightly related question to this one and this one . Basically, I would like
Although slightly related to a previous question, it is different. How secure is this
I realize that this question is slightly server related and could be posted on
Slightly related to this question , but you don't really need to read that.
Related to this question, but slightly different and hopefully more clear. I am looking
This is perhaps related to this question , but I have slightly more information.
slightly related to this question here . My problem: I am writing a bit
[Disclosure: This question is slightly related to my previous question .] As you can
This is slightly related to the question asked here yet the answer does not
This is a slightly tricky question. I am using NSDateFormatter on the iPhone but

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.