Why does adding the 'type' field to Argparse change it's behavior?

Question:

I have been following the example outlined in this previous question. But the behavior changes when I specify a type and I don’t understand why?

parser.add_argument('--bar', nargs='?', default=None, const=True)
args = parser.parse_args(['--bar=False'])
#Prints False as a string
print(args.bar)


parser.add_argument('--bar', nargs='?', default=None, const=True, type=bool)
args = parser.parse_args(['--bar=False'])
#Prints True as a bool
print(args.bar)

It’s not clear to me why in the first example ‘False’ overrides the const value of True but in the second example it does not?

Asked By: knowads

||

Answers:

When you say "type=bool", the criterion becomes "is it present or not". You specified --bar, so it was present, and the result is True. If you leave it out, the result will be False.

Usually, that’s exactly what you want. You don’t want people to type --bar==True or --bar==False. You want either --bar or no bar.

Answered By: Tim Roberts

The Documentation is often helpful…

By default, the parser reads command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, such as a float or int. The type keyword for add_argument() allows any necessary type-checking and type conversions to be performed.

Also, you should note that:

The bool() function is not recommended as a type converter. All it does is convert empty strings to False and non-empty strings to True. This is usually not what is desired.

Answered By: BeRT2me
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.