Categories
Python Answers

How to parse boolean values with argparse in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *