Fixing argparse TypeError caused by using nargs with store_true

Summary

A developer combined *`nargs=’** with an **action=”store_true”** (or“count”). argparseraisedTypeError: _StoreTrueAction.init() got an unexpected keyword argument ‘nargs’. The root cause is a **misunderstanding of mutually exclusive argument configurations** in theargparse` library.

Root Cause

  • store_true (and store_false, count) are flag actions that do not accept a value.
  • nargs tells the parser how many positional values to consume for an argument.
  • When action is a flag, argparse creates a specialized action class (_StoreTrueAction) whose constructor does not define a nargs parameter.
  • Supplying nargs therefore triggers the TypeError.

Why This Happens in Real Systems

  • API surface confusion: add_argument accepts many parameters, but not all are compatible with every action.
  • Copy‑paste errors: Developers often duplicate a working option and tweak only the name, inadvertently preserving incompatible flags.
  • Lack of validation: argparse only raises an error at runtime when the conflicting parameters are combined, which can slip through unit tests that never invoke the offending command line.

Real-World Impact

  • Service startup failures when a CLI wrapper is used to launch daemons with boolean flags that incorrectly specify nargs.
  • Operator confusion: The traceback mentions an obscure internal class (_StoreTrueAction), making it hard for non‑Python experts to diagnose.
  • Deployment rollbacks because a recent commit added a new flag with the incorrect combination, breaking CI pipelines.

Example or Code (if necessary and relevant)

import argparse

parser = argparse.ArgumentParser()
# Incorrect: flag action with nargs
parser.add_argument('-c', '--create', nargs='*', action='store_true')

How Senior Engineers Fix It

  • Replace the flag with a proper boolean option:
    parser.add_argument('-c', '--create', action='store_true')
  • If multiple values are needed, use a value‑accepting action such as store or append:
    parser.add_argument('-c', '--create', nargs='*', action='store')
  • Add validation tests that invoke the CLI with each flag to catch incompatible argument definitions early.
  • Document the allowed combos in an internal style guide:
    • store_true/store_false/countno nargs, type, or choices.
    • store/append → may use nargs, type, choices, etc.

Why Juniors Miss It

  • Overreliance on IDE autocomplete: IDEs suggest all parameters without indicating contextual incompatibilities.
  • Missing mental model of how flag actions differ from value‑accepting actions.
  • Insufficient hands‑on experience with the argparse source code, where the incompatibility is enforced only inside the action class constructors.
  • Pressure to ship quickly, leading to copy‑paste of existing argument definitions without reviewing semantics.

Leave a Comment