0

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.

5
  • You can make def_value a list? Commented Aug 13, 2021 at 14:35
  • 1
    Or you could omit nargs then you'll always get a string Commented Aug 13, 2021 at 14:36
  • 1
    why did you specify nargs=1? Do you understand what that does? Commented Aug 13, 2021 at 15:57
  • @sabik: Its the best move in my case. Thank you. Commented Aug 13, 2021 at 16:50
  • @hpaulj: Aparently, no ! Thanks, removing nargs fixed the issue. Commented Aug 13, 2021 at 16:52

2 Answers 2

1

did you try to remove the nargs option?

Sign up to request clarification or add additional context in comments.

1 Comment

I did it now. Easy fix ever. I copy/past and didn't realize nargs caused this.
1

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

1 Comment

I've copy/paste from other line and didn't realize nargs cause this behaviour. Removing the nargs is the best move in my case. Thank you.

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.