Technical skill practice
Python argparse: Parse Typed Options and Check Invalid Input
Python argparse turns command-line arguments into named values and reports invalid usage. Define positional arguments and optional flags, including types and allowed choices. The example uses an explicit argument list so valid input, help text and rejected input can all be checked without relying on your terminal arguments.
Start with a small, explicit task
A fictional summarizer accepts either short or full mode plus an optional count. Parse one valid call, inspect its help and deliberately reject a noninteger count. The count here controls a returned description only; there are no source files or external services.
Run the complete example
This original example was checked with Python 3.12.14. Save it as python_argparse.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.
Expected output
mode=short; count=5
help checked; invalid integer rejected
import argparse
import contextlib
import io
parser = argparse.ArgumentParser(prog="summarize")
parser.add_argument("mode", choices=["short", "full"])
parser.add_argument("--count", type=int, default=3)
args = parser.parse_args(["short", "--count", "5"])
assert (args.mode, args.count) == ("short", 5)
assert "--count" in parser.format_help()
assert "short" in parser.format_help()
errors = io.StringIO()
with contextlib.redirect_stderr(errors):
try:
parser.parse_args(["full", "--count", "many"])
except SystemExit as exc:
assert exc.code == 2
else:
raise AssertionError("expected parser rejection")
assert "invalid int value" in errors.getvalue()
print(f"mode={args.mode}; count={args.count}")
print("help checked; invalid integer rejected")
Explain the result
The required positional mode must match one of the two choices. --count is optional, and type=int makes the valid text 5 become an integer before application logic uses it. The help check verifies that the interface exposes those options without fixing the entire help layout to one exact formatting version.
The malformed count is rejected with exit status 2 through SystemExit. The script captures stderr locally and checks the relevant error phrase. A normal command-line program would usually let argparse display that message and exit; catching it here makes the failure path part of a repeatable teaching exercise.
Avoid these mistakes
Type conversion is not complete business validation. An integer count can still be negative or too large for your task, so enforce a stated range separately when required. For a real command-line entry point, parse_args() without the explicit fixture list reads the command’s arguments; retain explicit lists in focused parser tests.
Questions, answered
How do I make an argument required?
A positional argument such as mode is required here. An optional flag has separate required configuration when that interface is appropriate.
Does type=int enforce a positive number?
No. It converts integer text; a positive-only rule needs an additional check.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.