classification
Title: Argparse complains argument required when default is provided
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.8
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Clint Olsen, eric.smith
Priority: normal Keywords:

Created on 2021-02-10 10:24 by Clint Olsen, last changed 2021-02-10 19:30 by Clint Olsen.

Messages (6)
msg386770 - (view) Author: Clint Olsen (Clint Olsen) Date: 2021-02-10 10:24
When I run the following program, I expect args.run to be 'foo' if no argument is specified on the command-line.

parser = argparse.ArgumentParser()

parser.add_argument('foo', default='bar')

args = parser.parse_args()

$ ./test
usage: test [-h] foo
test: error: the following arguments are required: foo

However if I specify nargs='*' this error goes away.

Maybe I'm missing something obvious, but this seems non-intuitive to me.
msg386771 - (view) Author: Clint Olsen (Clint Olsen) Date: 2021-02-10 10:26
Sorry, I meant to say args.foo should be 'bar'.
msg386781 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-02-10 14:27
Providing a default value does not imply setting nargs, so you need to specify both. I think it's not clear what nargs would default to, if you wanted to change the behavior if default= is supplied.. In your example you probably want nargs='?', not '*'.
msg386799 - (view) Author: Clint Olsen (Clint Olsen) Date: 2021-02-10 19:14
Do you think it's unreasonable/unintuitive to infer nargs from the default value?
msg386801 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-02-10 19:19
Would you infer it to be ‘?’ or ‘*’?

I’m not completely opposed, but I haven’t thought it through or looked at the code.
msg386802 - (view) Author: Clint Olsen (Clint Olsen) Date: 2021-02-10 19:30
I think your original suggestion makes sense: '?'

My intuition is that nargs helps argparse discern whether it's dealing with single or multiple values. That may not be what was intended.

There probably shouldn't be multiple ways of indicating an argument is optional. It seems that required= and nargs='?'|'*' combinations could lead to conflicting requirements.
History
Date User Action Args
2021-02-10 19:30:28Clint Olsensetmessages: + msg386802
2021-02-10 19:19:01eric.smithsetmessages: + msg386801
2021-02-10 19:14:39Clint Olsensetmessages: + msg386799
2021-02-10 14:27:41eric.smithsetnosy: + eric.smith
messages: + msg386781
2021-02-10 10:26:12Clint Olsensetmessages: + msg386771
2021-02-10 10:24:37Clint Olsencreate