2

here is a simple example.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action = 'append_const', dest = 'letter', const = 'a')
parser.add_argument('-b', action = 'append_const', dest = 'letter', const = 'b')
parser.set_defaults(letter = ['a', 'b'])
print(parser.parse_args('-a'.split()))
print(parser.parse_args('-b'.split()))
print(parser.parse_args(''.split()))

Results :

Namespace(letter=['a', 'b', 'a'])
Namespace(letter=['a', 'b', 'b'])
Namespace(letter=['a', 'b'])

Without the set_defaults line, results are :

Namespace(letter=['a'])
Namespace(letter=['b'])
Namespace(letter=None)

How is it possible to configure argparse for such results ?

Namespace(letter=['a'])
Namespace(letter=['b'])
Namespace(letter=['a', 'b'])

2 Answers 2

1

As others have mentioned, store_const almost does what you want, except that (as @Theodros Zelleke points out) -ab would not be parsed correctly. I think the simplest way to address that problem is to simply handle the case of no arguments after parse_args has been called:

import argparse
import sys

def parse_args(argv = sys.argv[1:]):
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', action = 'append_const', dest = 'letter', const = 'a')
    parser.add_argument('-b', action = 'append_const', dest = 'letter', const = 'b')
    args = parser.parse_args(argv)
    if args.letter is None:
        args.letter = ['a','b']
    return args

print(parse_args('-a'.split()))
print(parse_args('-b'.split()))
print(parse_args('-ab'.split()))
print(parse_args(''.split()))

yields

Namespace(letter=['a'])
Namespace(letter=['b'])
Namespace(letter=['a', 'b'])
Namespace(letter=['a', 'b'])
Sign up to request clarification or add additional context in comments.

1 Comment

This is the solution I used. So, there is no solution using argparse defaults possiblities.
0

You should store the const instead of appending it, use the action 'store_const' (doc):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action = 'store_const', dest = 'letter', const = 'a')
parser.add_argument('-b', action = 'store_const', dest = 'letter', const = 'b')
parser.set_defaults(letter = ['a', 'b'])
print(parser.parse_args('-a'.split()))
print(parser.parse_args('-b'.split()))
print(parser.parse_args(''.split()))

This will result in:

Namespace(letter='a')
Namespace(letter='b')
Namespace(letter=['a', 'b'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.