Skip to content

Python Argparse Argument Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python Argparse Argument Error Fix. We cover key concepts, practical examples, and best practices.

Argparse raises errors like "unrecognized arguments", "expected one argument", or "invalid int value" when the command-line input does not match the defined arguments. These occur when argument names are wrong, types mismatch, or required arguments are missing.

The Problem

python script.py --name John --age twenty

Error:

usage: script.py [-h] --name NAME --age AGE
script.py: error: argument --age: invalid int value: 'twenty'

Wrong Code

import argparse

# WRONG — no type validation, no required check
parser = argparse.ArgumentParser()
parser.add_argument('--name')
parser.add_argument('--age')
args = parser.parse_args()

print(f"Name: {args.name}, Age: {args.age}")

Right Code

import argparse

parser = argparse.ArgumentParser(description='Process user data')
parser.add_argument('--name', required=True, help='User name')
parser.add_argument('--age', type=int, required=True, help='User age')
parser.add_argument('--verbose', action='store_true', help='Enable verbose')

args = parser.parse_args()
print(f"Name: {args.name}, Age: {args.age}")

Expected output with correct input:

python script.py --name John --age 25
Name: John, Age: 25

Step-by-Step Fix

Step 1: Use type parameter for validation

parser.add_argument('--port', type=int, default=8080)
parser.add_argument('--rate', type=float, default=1.0)

Step 2: Add choices for restricted values

parser.add_argument('--mode', choices=['dev', 'prod', 'test'], default='dev')

Step 3: Handle missing arguments

# Use default values
parser.add_argument('--output', default='output.txt')

# Or make required
parser.add_argument('--input', required=True)

Step 4: Parse multiple values

parser.add_argument('--files', nargs='+', help='List of files')
# Usage: --files a.txt b.txt c.txt

parser.add_argument('--count', nargs='?', const=1, type=int)
# --count     → 1 (const value)
# --count 5   → 5
# (not given) → None

Step 5: Handle positional arguments

parser.add_argument('input_file', help='Input file path')
parser.add_argument('output_file', nargs='?', default='output.txt')

Step 6: Custom validation function

def positive_int(value):
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(f"{value} is not positive")
    return ivalue

parser.add_argument('--count', type=positive_int)

Step 7: Handle subcommands

subparsers = parser.add_subparsers(dest='command')

parser_create = subparsers.add_parser('create')
parser_create.add_argument('--name', required=True)

parser_delete = subparsers.add_parser('delete')
parser_delete.add_argument('--id', type=int, required=True)

args = parser.parse_args()

Prevention Tips

  • Always set type for numeric arguments
  • Use choices for enum-like arguments
  • Set required=True for mandatory arguments
  • Provide helpful help text for every argument
  • Test argument parsing with different input combinations

Common Mistakes with argparse error

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between positional and optional arguments?

Positional arguments (no -- prefix) are required by default and ordered by position. Optional arguments (with -- prefix) are optional by default and can appear in any order. Use positional for the main input and optional for configuration flags.

How do I handle boolean flags in argparse?

Use action='store_true' (default False) or action='store_false' (default True). Example: --verbose sets args.verbose = True. Do not use type=bool — it treats any non-empty string as True.

How do I parse arguments without sys.argv?

Call parser.parse_args(['--name', 'John', '--age', '25']) with a list of strings. This is useful for testing argument parsing without the command line. The default parse_args() reads from sys.argv[1:].

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro