Sometim,es, we want to parse boolean values with argparse in Python.
In this article, we’ll look at how to parse boolean values with argparse in Python.
How to parse boolean values with argparse in Python?
To parse boolean values with argparse in Python, we can call add_argument with the action argument.
For instance, we write
parser.add_argument('--feature', action=argparse.BooleanOptionalAction)
to parse the --feature argument as a boolean by setting action to argparse.BooleanOptionalAction.
This works with Python 3.9 or later.
With older versions of Python, we write
parser.add_argument('--feature', action='store_true')
to call add_argument to parse the --feature argument as a boolean by setting action to 'store_true'.
Conclusion
To parse boolean values with argparse in Python, we can call add_argument with the action argument.