Temporary Advertisements:
Ad
Ad
Ad
Python argparse: why type=bool misreads False and how to make an on/off flag
by nolookshot - Friday October 16, 2026 at 04:06 PM
#1
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':
 
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 --verbose

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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make a call attack for free Manfruity 21 3,112 1 hour ago
Last Post: tetegix230
  Read any book for free Manfruity 6 5,005 1 hour ago
Last Post: ad3tak
  Python CSV: preserve quoted commas and multiline fields with DictReader nolookshot 0 59 3 hours ago
Last Post: nolookshot
  Useful links for developers Manfruity 56 7,474 3 hours ago
Last Post: nolookshot
  ✅ HOW TO GET ANY STEAM GAME FOR FREE ✅ UHQ METHOD ✨ DECEMBER 2023 artikino 10 3,434 Yesterday, 03:38 PM
Last Post: Chjvimiiic

Forum Jump:


 Users browsing this forum: 5 Guest(s)