Skip to content

Commit 5e1bf35

Browse files
[3.15] gh-155403: Clarify argparse default precedence (GH-160064) (#160259)
gh-155403: Clarify argparse `default` precedence (GH-160064) (cherry picked from commit 1705e51) Co-authored-by: Savannah Ostrowski <savannah@python.org>
1 parent 08fd98b commit 5e1bf35

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
@@ -789,6 +789,9 @@ how the command-line arguments should be handled. The supplied actions are:
789789
>>> parser.parse_args('--foo --bar'.split())
790790
Namespace(foo=True, bar=False, baz=True)
791791

792+
These defaults apply when the options are absent. They can be overridden
793+
by default_ or argument_default_.
794+
792795
* ``'append'`` - This appends each argument value to a list.
793796
It is useful for allowing an option to be specified multiple times.
794797
If the default value is a non-empty list, the parsed value will start
@@ -1012,10 +1015,8 @@ default
10121015

10131016
All optional arguments and some positional arguments may be omitted at the
10141017
command line. The ``default`` keyword argument of
1015-
:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
1016-
specifies what value should be used if the command-line argument is not present.
1017-
For optional arguments, the ``default`` value is used when the option string
1018-
was not present at the command line::
1018+
:meth:`~ArgumentParser.add_argument` specifies what value should be used if the
1019+
command-line argument is not present. For example::
10191020

10201021
>>> parser = argparse.ArgumentParser()
10211022
>>> parser.add_argument('--foo', default=42)
@@ -1024,6 +1025,11 @@ was not present at the command line::
10241025
>>> parser.parse_args([])
10251026
Namespace(foo=42)
10261027

1028+
If ``default`` is omitted, :meth:`~ArgumentParser.add_argument` uses a value
1029+
previously set for the dest_ with :meth:`~ArgumentParser.set_defaults`, or
1030+
otherwise a non-``None`` argument_default_. If neither is set, the action's
1031+
own default is used.
1032+
10271033
If the target namespace already has an attribute set, the action *default*
10281034
will not overwrite it::
10291035

0 commit comments

Comments
 (0)