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.
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:
If the user runs:
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.
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.
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.
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:
- convert the raw string
- validate the converted value
- raise
ArgumentTypeErrorwith a useful message if invalid
For example:
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.
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
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:
Less helpful:
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
typefunction to constrainargparsevalues cleanly. - Raise
argparse.ArgumentTypeErrorfor invalid input. - Use
choicesfor 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.
Related reading
- How can I convert a character to a integer in Python, and viceversa?
- How can I convert a datetime object to milliseconds since epoch unix time in Python?
- How can I convert a dictionary into a list of tuples?
- How can I convert a .py to .exe for Python?
- How can I convert an RGB image into grayscale in Python?
- How can I convert each item in the list to string, for the purpose of joining them?
- How can I convert TFRecords into numpy arrays?
- How can I create a copy of an object in Python?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.