python / python/cpython

Argparse: inconsistent default handling between `nargs` values

Open
#132,717 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:
import argparse

parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

day_names = ["mo", "tu", "we", "th", "fr", "sa", "su"]
days = [1, 2, 3, 4, 5, 6, 7]

def name_day(value):
    return day_names.index(value) + 1

parser.add_argument(
    '--day',
    type=name_day,
    default="mo",
    nargs='?',  
    help="pick a day",
)
args = parser.parse_args()
print(args.day)
Actual results:

The above code block will print the value 1. However, if we change the arguments to

    default=["mo"],
    nargs='+',

The code will print the value ["mo"]. So it seems type conversion does not happen for default arguments when nargs specifies multiple arguments.

Expected results:

The supplied default values are converted, irrespective of the value of nargs.

CPython versions tested on:

3.13, 3.10

Operating systems tested on:

Linux

Linked PRs
  • gh-132724

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the example with argparse and compare the default handling for nargs='?' and nargs='+'. Trace the argparse argument-processing entry point to see where type conversion differs, then verify that supplied defaults are converted consistently for both forms and preserve the expected parsed values.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.