1

I'm not quite understanding the following behavior of argparse

parser.add_argument("-option1", type=int, nargs='?', const=1, default=1, choices=xrange(1, 20), help="help message of option1")
parser.add_argument("-option2", type=str, nargs=1, help="help message of option2")

in case of option1, args.option1 is an integer, when provided. in case of option2, args.option2 looks like an array of strings. I have to use args.option2[0] if I want to get the actual string passed with option2

1 Answer 1

1

This is explained directly in the documentation on nargs. Summarizing:

For nargs=N, if N is an integer, you get a list of N values. Even if N is 1.

For nargs='?', you get a single value (which may be the default).

For nargs left off entirely, you get whatever the default is for the action. If the action is, e.g., store, that means a single value, not a list of one value.

It even explicitly points out exactly the part that's surprised you:

Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.

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

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.