Give an optional CLI count a typed default

An optional count often needs a useful value whether or not a caller writes the option. type=int converts a supplied command-line token, while default=3 supplies an integer directly when --count is absent. The example parses two synthetic invocations: the first models an omitted option and produces 3; the second models --count 5 and produces 5. The assertions verify the values and confirm that both results are int instances before arithmetic uses them.

Using an integer object as the default matters: a string default such as "3" can make downstream type expectations less obvious. type=int will reject non-integer textual input through argparse's normal error path, but it does not impose business rules such as a positive upper bound. Add choices, a custom converter, or post-parse validation if zero, negatives, or excessively large counts are invalid for the application. The output prints both parse results rather than claiming a real shell invocation occurred.

argparse is standard library functionality available from Python 3.2. Its official documentation describes default, and the type section describes conversion of command-line values.

AI assistance disclosure: this article was drafted with AI assistance and should be checked in its target CLI context.

import argparse

parser = argparse.ArgumentParser(prog="repeat")
parser.add_argument("--count", type=int, default=3)

default_args = parser.parse_args([])
provided_args = parser.parse_args(["--count", "5"])
assert default_args.count == 3
assert provided_args.count == 5
assert isinstance(default_args.count, int)
assert isinstance(provided_args.count, int)

print(f"default={default_args.count}")
print(f"provided={provided_args.count}")
default=3
provided=5

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic