How to Validate CLI Integer Option Within a Range in Python
Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.
Python code
17 linesimport argparse
def main():
parser = argparse.ArgumentParser(description="Validate an integer within a range.")
parser.add_argument("--value", type=int, required=True, help="Integer to validate")
parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
parser.add_argument("--max", type=int, default=100, help="Maximum allowed value")
args = parser.parse_args()
if not (args.min <= args.value <= args.max):
raise SystemExit(
f"Error: value {args.value} out of range [{args.min}, {args.max}]"
)
print(f"Valid: {args.value} is within [{args.min}, {args.max}]")
if __name__ == "__main__":
main()
Output
$ python app.py --value 50
Valid: 50 is within [0, 100]
$ python app.py --value 150
Error: value 150 out of range [0, 100]
How it works
The type=int parameter in add_argument converts the CLI string to an integer immediately. The script then compares the parsed value against the min and max defaults using Python's chained comparison operator. If the value falls outside the range, SystemExit terminates the program with a clear error message. The required=True flag ensures the user supplies a --value argument, preventing a missing-argument crash.
Common mistakes
- Calling `parser.parse_args()` inside `main()` but referencing `args` before the parser is fully defined.
- Forgetting to set `required=True` on the value argument, allowing a missing value to slip through.
- Using separate `if` statements instead of the chained comparison, making the logic harder to read.
Variations
- Use `type=lambda x: int(x)` to add custom validation logic before the range check.
- Implement range validation directly inside a custom `argparse.Action` class for reuse.
Real-world use cases
- Enforcing page-size limits on a paginated API client CLI tool.
- Validating port numbers in a network diagnostic script before opening a socket.
- Checking that an age or expiry period in a batch processing job stays within business rules.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.