Because type=bool applies Python’s truth test to the string False, and that string is nonempty. To accept explicit true or false values, use a converter that recognizes only the spellings your command promises to support. The example below accepts true and false, in any letter case; other words are errors.
Diagnose the value that reaches bool
With parser.add_argument('--enabled', type=bool), argparse passes the text following --enabled to bool. Python considers a nonempty string true, so False, false, and even no all produce True. The documented argparse example shows this exact result for False. An empty string is false, but that is rarely the intended command-line spelling for a disabled setting.
This diagnosis applies to an option that consumes a value. If the intended interface is a switch users write without a following word, use a flag action; the companion article compares those actions. Changing the default does not repair type=bool when the user supplies False, because the supplied text is still converted.
Sources: argparse — Parser for command-line options, arguments and subcommands — type, Built-in Types — Truth Value Testing — Truth Value Testing
Accept a defined true or false vocabulary
Use a callable converter and raise argparse.ArgumentTypeError for anything outside its vocabulary. Here is a runnable example for Python 3.13; it is illustrative code, not a reported local test:
import argparse def parse_bool(value): normalized = value.casefold() if normalized == 'true': return True if normalized == 'false': return False raise argparse.ArgumentTypeError('expected true or false') parser = argparse.ArgumentParser() parser.add_argument('--enabled', type=parse_bool, default=None) args = parser.parse_args() print(args.enabled)
This policy deliberately rejects 1, 0, yes, no, and blank text. Add spellings only if they belong in your interface contract. The type hook receives one string, and argparse documents ArgumentTypeError as a supported way to report a conversion failure. With the ordinary parser settings, invalid arguments produce usage and an error and exit with status 2. The message above states the accepted words without silently treating an unfamiliar value as true.
Sources: argparse — Parser for command-line options, arguments and subcommands — type; exit_on_error, Built-in Types — Truth Value Testing — str.casefold
Read the input and result matrix
The following results are derived from the displayed converter and the documented parser rules; they were not executed for this article. The explicit default=None keeps omission distinct from an explicit false value. If your application should start disabled, change that default to False. If it must know whether the user made a choice, retain None and check it separately from truthiness.
The table concerns the converter above, not type=bool. Its error row means argparse reports the converter’s message; exact surrounding usage text depends on the program name and other arguments.
| Input | Illustrative result | Interpretation |
|---|---|---|
| option omitted | None | No explicit choice |
| --enabled true | True | Enabled explicitly |
| --enabled FALSE | False | Disabled explicitly |
| --enabled maybe | Parser error: expected true or false | Rejected vocabulary |
| --enabled with no value | Parser error: expected one argument | Missing value |
Sources: argparse — Parser for command-line options, arguments and subcommands — default; type; Invalid arguments
Primary sources checked: 2026-11-02. Prepared with AI assistance and a separate evidence review. This is documentation-based guidance, not a hands-on test or performance benchmark.
Reproduce the locally verified result
argparse-local-v1
Recorded environment: 3.12.13 / Darwin. Checked: 2026-11-05T05:15:42.268392+00:00
import argparse
p = argparse.ArgumentParser()
p.add_argument("--enabled", type=bool)
print("type=bool, False:", p.parse_args(["--enabled", "False"]).enabled)
def parse_bool(value):
if value.casefold() in ("true", "false"):
return value.casefold() == "true"
raise argparse.ArgumentTypeError("expected true or false")
p = argparse.ArgumentParser()
p.add_argument("--enabled", type=parse_bool, default=None)
for argv in ([], ["--enabled", "true"], ["--enabled", "False"]):
print(repr(argv), "->", p.parse_args(argv).enabled)Observed output
type=bool, False: True
[] -> None
['--enabled', 'true'] -> True
['--enabled', 'False'] -> False
Only this fixed synthetic fixture was tested on the recorded runtime. No production files, other OS/version combinations, UI applications, throughput or performance were tested.
댓글 없음:
댓글 쓰기