Python: Validate only the selected argparse subcommand
argparse can validate related options after parsing, but each subcommand has its own namespace. Check the selected command before reading its attributes, and report a cross-field error through that subcommand’s parser.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as command_validation_demo.py in an empty working directory:
import argparse
import contextlib
import io
parser = argparse.ArgumentParser(prog="report")
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("status")
export = commands.add_parser("export")
export.add_argument("--start", type=int, required=True)
export.add_argument("--end", type=int, required=True)
def parse(argv):
args = parser.parse_args(argv)
if args.command == "export" and args.start > args.end:
export.error("--start must not exceed --end")
return args
print("Status:", vars(parse(["status"])))
print("Export:", vars(parse(["export", "--start", "2", "--end", "5"])))
errors = io.StringIO()
with contextlib.redirect_stderr(errors):
try:
parse(["export", "--start", "8", "--end", "3"])
except SystemExit as exc:
print("Rejected exit:", exc.code)
print(errors.getvalue().splitlines()[-1])Run it without -O so any assertions remain enabled:
python3 command_validation_demo.pyCaptured output:
Status: {'command': 'status'}
Export: {'command': 'export', 'start': 2, 'end': 5}
Rejected exit: 2
report export: error: --start must not exceed --endstatus has no start or end attributes. The command check prevents an attribute error, while type=int handles individual conversions before the range check runs. Calling export.error() prints the export usage and exits with status 2; the example captures that expected error so all cases run.
Limits and cleanup
Keep parsing and validation before file creation or other side effects. This example validates an integer interval only; it does not create a report. For a real CLI, let the parser’s error reach the terminal instead of capturing it.
After testing, remove the example script from its working directory:
rm -- command_validation_demo.pyReference
Acknowledgements
This post was created with assistance from AI.