Python Glossary Русский

Python 3.9+argparseterm

argparse.BooleanOptionalAction

actions

An action for an on/off flag: a single --feature option creates the pair --feature / --no-feature, which set True and False.

Syntax

parser.add_argument('--feature', action=argparse.BooleanOptionalAction)

It fixes the classic type=bool mistake: bool('False') is True because any non-empty string is truthy, so '--flag False' turns the flag on. Without a default the value is None, not False: that tells 'not given' apart from 'switched off', but an 'is False' check will miss it. Set default=False explicitly if that is what you want.

Examples

import argparse
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--color', action=argparse.BooleanOptionalAction)
print(parser.parse_args([]))  # → Namespace(color=None)
print(parser.parse_args(['--no-color']))  # → Namespace(color=False)
import argparse
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--flag', type=bool)
print(parser.parse_args(['--flag', 'False']))  # → Namespace(flag=True) — ловушка type=bool

See also

Open in the full glossarydocs.python.orgReport an inaccuracy