Skip to content

Parsing boolean values with argparse

Here is an example of how to parse boolean values with argparse in Python:

Parse boolean values with argparse in Python

python
import argparse

def str_to_bool(value):
    return value.lower() in ('true', '1', 'yes')

parser = argparse.ArgumentParser()
parser.add_argument('--flag', type=str_to_bool, default=True, help='A boolean flag')
args = parser.parse_args()
print(args.flag)

In this example, we create an ArgumentParser object and add a boolean argument --flag using the add_argument() method. Since command-line arguments are passed as strings, we use a custom type converter instead of bool to safely parse them. The default parameter is set to True, and the help parameter provides a brief description. We then parse the command-line arguments using the parse_args() method and access the value of the --flag argument using the args.flag attribute.

You can run this script with different inputs to see how it works:

console
$ python script.py --flag true
True

$ python script.py --flag false
False

This is just a simple example, and argparse provides many more features for more complex command-line interfaces.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.