Skip to content
Advertisement

Parsing boolean values with argparse

I would like to use argparse to parse boolean command-line arguments written as “–foo True” or “–foo False”. For example:

JavaScript

However, the following test code does not do what I would like:

JavaScript

Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evalutates to False.

How can I get argparse to parse "False", "F", and their lower-case variants to be False?

Advertisement

Answer

This is actually outdated. For Python 3.7+, Argparse now supports boolean args (search BooleanOptionalAction).

The implementation looks like this:

JavaScript

One other thing to mention: this will block all entries other than True and False for the argument via argparse.ArgumentTypeError. You can create a custom error class for this if you want to try to change this for any reason.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement