How do you specify a default value and a type conversion for an argument?
Short answer
Pass 'default=' to set the value used when the argument is omitted, and 'type=' to specify a callable (like int, float, or a custom function) that argparse applies to convert the raw string input — argparse automatically raises a helpful error if the conversion fails.
Advertisement
AModel answer
Pass 'default=' to set the value used when the argument is omitted, and 'type=' to specify a callable (like int, float, or a custom function) that argparse applies to convert the raw string input — argparse automatically raises a helpful error if the conversion fails.
parser.add_argument("--count", type=int, default=1, help="Number of times to repeat")
args = parser.parse_args(["--count", "5"])
print(args.count) # 5 (an actual int, not the string '5')Real-world example
Accepting a numeric --count or --port argument that's automatically validated and converted to an int, with a sensible default.
Likely follow-ups
- What error does argparse raise (and how does it exit) if the user passes a non-numeric value for a type=int argument?
Related topics