Miguel Rozsas
Miguel Rozsas

Reputation: 427

python argparse default arguments versus given arguments

Using python 3.8 argparse:

def_value= 'whatever'
argParser.add_argument ("-w", "--whatever", type=str, nargs=1, default=def_value, help="Whatever. Defaults to %s"  % def_value)
args= argParser.parse_args()
print (args.whatever)

If I call my program passing a option -w with a value, args.whatever is a list. I mean:

myprog -w just_a_test
[just_a_test]

but, I pass nothing, the default argument is a string.

myprog
whatever

This is annoying, I mean, I have to test the type of args.whatever before using it; If it is a is a string, just use it as string; if it is a list, I have to use it as args.whatever[0], you see ?

What is the best way to deal with such thing ?

PS: I think it is specific to 3.x, as I recall 2.x returned strings all the time.

Upvotes: 0

Views: 69

Answers (2)

seermer
seermer

Reputation: 651

using n_args parameter will wrap the value in a list, therefore, there are two options:
1. remove nargs argument.

def_value= 'whatever'
argParser.add_argument("-w", "--whatever", type=str, default=def_value, help="Whatever. Defaults to %s"  % def_value)
args= argParser.parse_args()
print(args.whatever)

argparse by default allows only one arg, so in this case, no matter passing an argument or not, you will always get a string, and you will get an error when you try to pass more than 1 value.

2.wrap def_value with a list:

def_value= ['whatever']
argParser.add_argument("-w", "--whatever", type=str, nargs=1, default=def_value, help="Whatever. Defaults to %s"  % def_value)
args= argParser.parse_args()
print(args.whatever)

now both default and passed in value will be a list with a single string, and it will also raise an error when you pass more than 1 value.

Both solutions above should accomplish the same goal, depending on which you prefer

Upvotes: 1

user6106573
user6106573

Reputation: 191

did you try to remove the nargs option?

Upvotes: 1

Related Questions