3 hours ago
A common command-line parsing trap is to use type=bool for an on/off option. Python treats every non-empty string as true, so the text 'False' also becomes True. That is usually surprising for someone running a script.
For a flag that is disabled by default and enabled by its presence, use action='store_true':
Save as flags_demo.py, then compare:
The first prints False and the second prints True. Do not append the word False to this presence-only flag; omit --verbose to leave it off. For a CLI that needs both --feature and --no-feature, the standard library also provides BooleanOptionalAction on Python 3.9 and later.
Reference: https://docs.python.org/3/library/argparse.html#action
For a flag that is disabled by default and enabled by its presence, use action='store_true':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', action='store_true')
assert parser.parse_args([]).verbose is False
assert parser.parse_args(['--verbose']).verbose is True
assert bool('False') is True
args = parser.parse_args()
print('Verbose mode:', args.verbose)Save as flags_demo.py, then compare:
python3 flags_demo.py
python3 flags_demo.py --verboseThe first prints False and the second prints True. Do not append the word False to this presence-only flag; omit --verbose to leave it off. For a CLI that needs both --feature and --no-feature, the standard library also provides BooleanOptionalAction on Python 3.9 and later.
Reference: https://docs.python.org/3/library/argparse.html#action
