Argparse: inconsistent default handling between `nargs` values
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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