Skip to content

Commit a2341ad

Browse files
[3.14] gh-155403: Clarify argparse default precedence (GH-160064) (#160260)
gh-155403: Clarify argparse `default` precedence (GH-160064) (cherry picked from commit 1705e51) Co-authored-by: Savannah Ostrowski <savannah@python.org>
1 parent a4aadcb commit a2341ad

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

‎Doc/library/argparse.rst‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,9 @@ how the command-line arguments should be handled. The supplied actions are:
785785
>>> parser.parse_args('--foo --bar'.split())
786786
Namespace(foo=True, bar=False, baz=True)
787787

788+
These defaults apply when the options are absent. They can be overridden
789+
by default_ or argument_default_.
790+
788791
* ``'append'`` - This appends each argument value to a list.
789792
It is useful for allowing an option to be specified multiple times.
790793
If the default value is a non-empty list, the parsed value will start
@@ -1008,10 +1011,8 @@ default
10081011

10091012
All optional arguments and some positional arguments may be omitted at the
10101013
command line. The ``default`` keyword argument of
1011-
:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
1012-
specifies what value should be used if the command-line argument is not present.
1013-
For optional arguments, the ``default`` value is used when the option string
1014-
was not present at the command line::
1014+
:meth:`~ArgumentParser.add_argument` specifies what value should be used if the
1015+
command-line argument is not present. For example::
10151016

10161017
>>> parser = argparse.ArgumentParser()
10171018
>>> parser.add_argument('--foo', default=42)
@@ -1020,6 +1021,11 @@ was not present at the command line::
10201021
>>> parser.parse_args([])
10211022
Namespace(foo=42)
10221023

1024+
If ``default`` is omitted, :meth:`~ArgumentParser.add_argument` uses a value
1025+
previously set for the dest_ with :meth:`~ArgumentParser.set_defaults`, or
1026+
otherwise a non-``None`` argument_default_. If neither is set, the action's
1027+
own default is used.
1028+
10231029
If the target namespace already has an attribute set, the action *default*
10241030
will not overwrite it::
10251031

0 commit comments

Comments
 (0)