argparse
Python
command-line
input validation
programming tutorial

How can I constrain a value parsed with argparse for example, restrict an integer to positive values?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

In argparse, the normal way to constrain parsed values is to validate them during parsing rather than after the fact. For numbers, the most common pattern is a custom type function that converts the string and raises argparse.ArgumentTypeError when the value is invalid. This gives users an immediate, consistent command-line error message and keeps validation close to the argument definition.

Use a Custom Type for Positive Integers

Here is the standard pattern:

python
1import argparse
2
3def positive_int(value: str) -> int:
4    ivalue = int(value)
5    if ivalue <= 0:
6        raise argparse.ArgumentTypeError(f"{value!r} is not a positive integer")
7    return ivalue
8
9parser = argparse.ArgumentParser()
10parser.add_argument("--count", type=positive_int, required=True)
11
12args = parser.parse_args()
13print(args.count)

If the user runs:

bash
python app.py --count -3

argparse will stop with a clean validation error instead of letting bad input leak further into the program.

Why type=int Alone Is Not Enough

Using type=int only checks that the input is parseable as an integer.

python
parser.add_argument("--count", type=int)

This accepts:

  • '5'
  • '0'
  • '-9'

If your domain requires a positive integer, you need an extra validation step. A custom type is usually the most direct way to do it.

Constraining Other Numeric Ranges

The same technique works for more specific rules such as non-negative values or bounded ranges.

python
1import argparse
2
3def port_number(value: str) -> int:
4    ivalue = int(value)
5    if not 1 <= ivalue <= 65535:
6        raise argparse.ArgumentTypeError(f"{value!r} is not a valid port number")
7    return ivalue
8
9parser = argparse.ArgumentParser()
10parser.add_argument("--port", type=port_number, default=8080)
11
12args = parser.parse_args()
13print(args.port)

This keeps the validation logic reusable and readable.

Use choices for Small Fixed Sets

If the valid values are a small finite set, choices is often better than a custom validator.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("--mode", choices=["fast", "safe", "debug"], required=True)
5
6args = parser.parse_args()
7print(args.mode)

choices is great for enumerated values, but it is not the right tool for open-ended numeric constraints such as “positive integer.”

Combine Parsing and Validation Carefully

A good custom type function should:

  1. convert the raw string
  2. validate the converted value
  3. raise ArgumentTypeError with a useful message if invalid

For example:

python
1import argparse
2
3def probability(value: str) -> float:
4    fvalue = float(value)
5    if not 0.0 <= fvalue <= 1.0:
6        raise argparse.ArgumentTypeError(f"{value!r} must be between 0 and 1")
7    return fvalue

This pattern scales well across many argument types.

Post-Parse Validation Is Still Possible

You can validate after parse_args(), but it is usually less elegant because you have to write custom error plumbing yourself.

python
args = parser.parse_args()
if args.count <= 0:
    parser.error("--count must be a positive integer")

This can be reasonable for validation that depends on multiple arguments together, but for single-argument constraints, custom type functions are cleaner.

Example with Multiple Validated Arguments

python
1import argparse
2
3def positive_int(value: str) -> int:
4    ivalue = int(value)
5    if ivalue <= 0:
6        raise argparse.ArgumentTypeError("value must be positive")
7    return ivalue
8
9def fraction(value: str) -> float:
10    fvalue = float(value)
11    if not 0.0 <= fvalue <= 1.0:
12        raise argparse.ArgumentTypeError("value must be between 0 and 1")
13    return fvalue
14
15parser = argparse.ArgumentParser()
16parser.add_argument("--workers", type=positive_int, default=4)
17parser.add_argument("--sample-rate", type=fraction, default=0.5)
18
19args = parser.parse_args()
20print(args)

This keeps the command-line interface strict without turning the main program body into a pile of manual checks.

Error Message Quality Matters

Your validator is part of the CLI user experience. Messages such as “invalid value” are weaker than messages that say exactly what was expected.

Good:

text
'-3' is not a positive integer

Less helpful:

text
invalid argument

Because argparse prints these messages directly to users, clear wording is worth the effort.

Common Pitfalls

The biggest mistake is assuming type=int automatically enforces positivity. Another is raising a generic exception instead of argparse.ArgumentTypeError, which can produce poor CLI output. Developers also often put all validation after parsing even when the rule belongs naturally to one argument. Finally, choices is great for small fixed sets but not a substitute for open-ended numeric range checks.

Summary

  • Use a custom type function to constrain argparse values cleanly.
  • Raise argparse.ArgumentTypeError for invalid input.
  • Use choices for small enumerated sets, not for general numeric ranges.
  • Reserve post-parse validation for rules that depend on multiple arguments together.
  • Make the error message specific so users know exactly how to fix the command.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms