python/cpython · error · ValueError

nargs must be %r to supply const

Error message

nargs must be %r to supply const

What it means

_StoreAction requires nargs to be '?' (OPTIONAL) when const is supplied, because const is only defined for the case where the option appears without a value. Supplying const with any other nargs (including None/default, '*', '+', or an int) is ambiguous and raises ValueError at parser-construction time.

Source

Thrown at Lib/argparse.py:1115

    def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None,
                 deprecated=False):
        if nargs == 0:
            raise ValueError('nargs for store actions must be != 0; if you '
                             'have nothing to store, actions such as store '
                             'true or store const may be more appropriate')
        if const is not None and nargs != OPTIONAL:
            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
        super(_StoreAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            const=const,
            default=default,
            type=type,
            choices=choices,
            required=required,
            help=help,
            metavar=metavar,
            deprecated=deprecated)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)


class _StoreConstAction(Action):

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Add nargs='?': add_argument('--foo', nargs='?', const='x', default='y').
  2. If you only need a value when absent, use default instead of const.
  3. For count-style flags, use action='count' or 'store_const' rather than const on a store action.

Example fix

# before
parser.add_argument('--log', const='verbose')  # ValueError: nargs must be '?' to supply const

# after
parser.add_argument('--log', nargs='?', const='verbose', default='info')
Defensive patterns

Strategy: validation

Validate before calling

def validate_const_nargs(const, nargs):
    if const is not None and nargs != '?':
        raise ValueError("const requires nargs='?'")

Prevention

When it happens

Trigger: parser.add_argument('--foo', const='x') without nargs='?'; parser.add_argument('--foo', const='x', nargs='*'); passing const through a wrapper that does not set nargs.

Common situations: Wanting a default-but-different value for a flag and forgetting nargs='?'; copy-pasting an argument spec and deleting the nargs line; dynamic argument builders that always forward const.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/9ea796f8eaa6e46b. Report an issue: GitHub.