Skip to main content

How to Accept Only Positive Integers in argparse

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

type=int makes an argparse option a whole number, but it happily accepts 0 and -5, which make no sense for a count. A small function passed as type does the conversion and the check in one place, and argparse turns its complaint into a proper error message. This guide builds a script that repeats a word a positive number of times, with real output from Python 3.15.2.

Syntax​

Syntax
def positive_int(text: str) -> int:
value = int(text)
if value < 1:
raise argparse.ArgumentTypeError(f"must be 1 or more, got {value}")
return value


parser.add_argument("--<option>", type=positive_int)
PartWhat it means
positive_int(text)argparse calls it with the option's text, such as "3", and uses what it returns
int(text)Converts the text; it raises ValueError for text such as "two"
argparse.ArgumentTypeError(...)"Raised when something goes wrong converting a command line string to a type"; its message becomes the error the user sees
type=positive_intUse the function, without brackets, as the option's type

The Python documentation explains the rule behind it: "If the function raises ArgumentTypeError, TypeError, or ValueError, the exception is caught and a nicely formatted error message is displayed."

Step 1: Write the Script​

The example prints a word several times. Create repeat.py:

The repeat.py script in a macOS-style code window: a positive_int function that converts its text with int and raises argparse.ArgumentTypeError when the value is below 1, a parser named repeat with a word argument and a --times option of type positive_int defaulting to 1, and a print that repeats the word.

repeat.py
import argparse


def positive_int(text: str) -> int:
"""Read a whole number of at least 1."""
value = int(text)
if value < 1:
raise argparse.ArgumentTypeError(f"must be 1 or more, got {value}")
return value


parser = argparse.ArgumentParser(prog="repeat", description="Print a word several times.")
parser.add_argument("word")
parser.add_argument("--times", type=positive_int, default=1, help="how many times (default: 1)")
args = parser.parse_args()

print(" ".join([args.word] * args.times))

Step 2: Run It with Good and Bad Values​

Terminal
uv run python repeat.py hello --times 3
uv run python repeat.py hello --times 0
uv run python repeat.py hello --times two
Output
hello hello hello
usage: repeat [-h] [--times TIMES] word
repeat: error: argument --times: must be 1 or more, got 0
usage: repeat [-h] [--times TIMES] word
repeat: error: argument --times: invalid positive_int value: 'two'

A terminal running repeat.py three times: --times 3 prints hello three times, --times 0 prints the usage line and error: argument --times: must be 1 or more, got 0, and --times two prints the usage line and error: argument --times: invalid positive_int value: 'two'.

InputWhat happened
--times 3positive_int returned 3, and the word printed three times
--times 0positive_int raised ArgumentTypeError; argparse printed the usage line and the function's own message
--times twoint("two") raised ValueError; argparse printed its standard message, naming the function: invalid positive_int value: 'two'

After an error, argparse stops the script with exit code 2, so shell scripts can tell the run failed.

Step 3: Check the Help​

Terminal
uv run python repeat.py --help
Output
usage: repeat [-h] [--times TIMES] word

Print a word several times.

positional arguments:
word

options:
-h, --help show this help message and exit
--times TIMES how many times (default: 1)

Without --times, the default, 1, is used, and the word prints once. A default that isn't text is used as it is, without going through positive_int.

Common Mistakes​

MistakeWhat happensDo this instead
type=positive_int(), with bracketsPython calls the function at once, without text, and stops with a TypeErrorPass the function itself: type=positive_int
Raising another exception, such as RuntimeErrorargparse doesn't catch it, and the user sees a tracebackRaise argparse.ArgumentTypeError
Checking the value after parse_args() with if and printThe check is far from the option, and the usage line isn't shownPut the check in the type function

Troubleshooting​

SymptomLikely causeFix
invalid positive_int value: 'two'The text isn't a whole numberPass digits, such as --times 2
must be 1 or more, got 0The number is below 1Pass 1 or more
The error names the function, positive_int, which users don't knowThat's argparse's message for a ValueErrorCatch the ValueError inside the function and raise ArgumentTypeError with your own words

FAQ​

Can I use the same function for several options?​

Yes. Any option can use type=positive_int, and each error names the option it came from.

What about an upper limit?​

Add a second check in the same function, such as if value > 100: raise argparse.ArgumentTypeError("must be 100 or less"). For a short list of allowed values, choices= is simpler.

Does this work for positional arguments?​

Yes: parser.add_argument("count", type=positive_int) works the same way.

Conclusion​

A positive_int function that converts with int() and raises argparse.ArgumentTypeError below 1, passed as type=positive_int, made --times refuse 0 with the function's own message and two with argparse's, and stop with exit code 2. One small function keeps the conversion and the check together.

Additional Resources​