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(andstore_false,count) are flag actions that do not accept a value.nargstells the parser how many positional values to consume for an argument.- When
actionis a flag,argparsecreates a specialized action class (_StoreTrueAction) whose constructor does not define anargsparameter. - Supplying
nargstherefore triggers theTypeError.
Why This Happens in Real Systems
- API surface confusion:
add_argumentaccepts 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:
argparseonly 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
storeorappend: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/count→ nonargs,type, orchoices.store/append→ may usenargs,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
argparsesource 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.