brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python argparse BooleanOptionalAction adds --flag and --no-flag in one line

Python
~/tips/tip-python-argparse-boolean-optional

import argparse

Generates a matching --no-flag for a boolean option, so users can switch defaults off.

Handwriting a --no-color twin for every switch gets old, so I let argparse generate it.

import argparse

p = argparse.ArgumentParser()
p.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
print(p.parse_args())

BooleanOptionalAction (Python 3.9 and later) registers both --color and --no-color and stores a real True or False. The help text shows both spellings automatically. Set default explicitly, because without it the value is None when neither flag is given. This beats store_true when the default is already on and users need a way to turn it off. Older code often reaches for two separate arguments with dest and opposite actions, which this replaces.

Further reading: argparse documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link