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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T17:45:33+00:00 2026-06-17T17:45:33+00:00

Using argparse (or something else?) I would like each positional argument to have an

  • 0

Using argparse (or something else?) I would like each positional argument to have an optional argument with default value.

The arguments would be as so:

script.py arg1 arg2 -o 1 arg3 -o 2 arg4 arg5

and I want it to parse this into something usable, like a list of the positional arguments and a list of the optional arguments with defaults filled in. e.g. if the default for the optional is 0 in the example above:

positional = [arg1, arg2, arg3, arg4, arg5]
optional = [0, 1, 2, 0, 0]

in other words, parser.add_argument('-o', action='append') is not what I want because I lose the positional argument, each optional argument is associated to.

  • 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-17T17:45:34+00:00Added an answer on June 17, 2026 at 5:45 pm

    Here’s a simple hack that I put together that might be a reasonable place to start:

    import argparse
    
    class PositionalAction(argparse.Action):
        def __call__(self,parser,namespace,values,option_string=None):
            lst = getattr(namespace,self.dest)
            lst.append(values)
            parser.last_positional_values = lst
            all_positional = getattr(namespace,'all_positional',[])
            all_positional.append(lst)
            namespace.all_positional = all_positional
    
    class AssociateAction(argparse.Action):
        def __call__(self,parser,namespace,values,option_string=None):
            try:
                parser.last_positional_values.append(values)
            except AttributeError:
                pass
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-o',action=AssociateAction,dest=argparse.SUPPRESS)
    junk,unknown = parser.parse_known_args()
    
    for i,_ in enumerate(unknown):
        parser.add_argument('arg%d'%i,action=PositionalAction,default=[])
    
    print parser.parse_args()
    

    And here it is in action:

    temp $ python test1.py foo -o 1 bar -o 2 baz qux -o 4
    Namespace(all_positional=[['foo', '1'], ['bar', '2'], ['baz'], ['qux', '4']], arg0=['foo', '1'], arg1=['bar', '2'], arg2=['baz'], arg3=['qux', '4'])
    

    This problem has a few challenges. First, You want to accept an arbitrary number of positional arguments — argparse doesn’t like that. argparse wants to know up front what to expect. The solution is to build a parser and parse the commandline, but to tell argparse to only parse the known arguments only (in this case, the non-positional -o arguments are all parsed silently but the “positional” arguments aren’t parsed.). parse_known_args is perfect for this as it returns a tuple in the form (namespace_of_parsed_stuff, uknown_args). So now we know the unknown arguments — We just need to add a positional argument to the parser for each one to make parse_args happy.

    Now, what are the custom actions actually doing? When a positional argument is found (on the second pass), we get the default (which is a list) and add the value to that list (hereafter I’ll call it the “value” list). We then modify the parser with a reference to the “value” list. We also get the “all_positional” list from the namespace. If it doesn’t have that attribute, we just get an empty list. We add the “value” list to the “all_positional” list and put it back on the namespace.

    Now, when we hit a -o flag, we look at the parser to get the “value” list and we add the additional value to that list. We could do the same thing without touching the parser at all … (we could look at namespace.all_positional[-1] — It’s the same list as parser.last_positional_values).

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

Sidebar

Related Questions

Is there a way to filetype-check filename arguments using argparse ? Seems like it
I am using Python's (2.7) argparse facility and would like to automatically sort the
I have a program that uses a default name and password. I'm using argparse
I would like use argparse to parse the arguments that it knows and then
For my project I would be using the argparse library. My question is, how
I have a python option parsers that parses an optional --list-something option. I also
I would like to parse arguments passed from the command line with the prefix
Using argparse , is it possible to stop parsing arguments at the first unknown
In a Python script, I would like to control the importing of a module
I'd like to display argparse help for my options the same way the default

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.