import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)
Answer from unutbu on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
Generally, argument defaults are specified either by passing a default to add_argument() or by calling the set_defaults() methods with a specific set of name-value pairs. Sometimes however, it may be useful to specify a single parser-wide default ...
Discussions

Why/how does "%(default)s" display default arg in argparse help text?
It's just % formatting syntax with named placeholders. More on reddit.com
🌐 r/learnpython
22
1
August 24, 2021
Argparse: "Default" interacts incorrectly/non-intuitively with action='append' and action='extend'
Argparse: "Default" interacts incorrectly/non-intuitively with action='append' and action='extend'#110131 ... 3.12only security fixesonly security fixes3.13bugs and security fixesbugs and security fixes3.14bugs and security fixesbugs and security fixesdocsDocumentation in the Doc dirDocumentation in the Doc dirstdlibStandard Library Python ... More on github.com
🌐 github.com
2
September 30, 2023
argparse default values
You're going to need to show some code here. More on reddit.com
🌐 r/learnpython
4
1
March 21, 2017
What's the point of argparse if you can use input?
A utility with arguments is easier to script/automate/run multiple times than one which takes input from stdin. It's still possible that way (just redirect stdin), but the former is much more convenient and aligns with existing conventions for CLI tools. More on reddit.com
🌐 r/learnpython
12
1
January 2, 2024
🌐
Reddit
reddit.com › r/learnpython › why/how does "%(default)s" display default arg in argparse help text?
r/learnpython on Reddit: Why/how does "%(default)s" display default arg in argparse help text?
August 24, 2021 -

Here is a snippet of example code. Pretend this is at the top of a file script.py:

import argparse

DEFAULT_ARG = 'How can a clam cram in a clean cream can?'

parser = argparse.ArgumentParser()
parser.add_argument('--some_arg',
                    default=DEFAULT_ARG,
                    help='some random argument (default: %(default)s)')
args = parser.parse_args()

If you then run python script.py --help, you see the following:

usage: script.py [-h] [--some_arg SOME_ARG]

optional arguments:
  -h, --help           show this help message and exit
  --some_arg SOME_ARG  some random argument (default: How can a clam cram in a clean cream can?)

Notice how in the final line, %(default)s was expanded to the value of DEFAULT_ARG, the default argument for args.some_arg. I saw this hack a year or so ago on SO as a way to get argparse to dynamically show an argument's default value without any bespoke modification to the ArgumentParser's formatter_class arg. I've done it this way ever since because it's so dead easy. But I never stopped to wonder how/why it actually works, until now.

Can someone explain what's going on? How does Python know that the default in the middle of the help string == the default argument going into parser.add_argument? I'm pretty proficient with Python but I guess underlyingly this is a feature I never learned about. Also, if there is a better/more recommended/more modern way to achieve the same (i.e., default values displayed in the help text), I'd love to know. Thanks!

🌐
GeeksforGeeks
geeksforgeeks.org › python › argparse-way-to-include-default-values-in-help
Argparse: Way to include default values in '--help'? - GeeksforGeeks
July 23, 2025 - There are several ways to achieve this, including using argparse.ArgumentDefaultsHelpFormatter and custom help formatters. Below are the ways to include default values in '--help' in Python.
🌐
GitHub
hplgit.github.io › primer.html › doc › pub › input › ._input-solarized004.html
Option-value pairs on the command line
All input variables should have sensible default values such that we can leave out the options for which the default value is suitable. For example, if \( s_0=0 \), \( v_0=0 \), \( a=1 \), and \( t=1 \) by default, and we only want to change \( t \), we can run ...
Find elsewhere
🌐
LabEx
labex.io › tutorials › python-how-to-set-argparse-default-values-451017
How to set argparse default values | LabEx
Default values provide a way to set predefined arguments when no specific value is provided by the user. Argparse offers multiple techniques to implement default values.
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.3 documentation
Remember that by default, if an optional argument isn’t specified, it gets the None value, and that cannot be compared to an int value (hence the TypeError exception). ... You can go quite far just with what we’ve learned so far, and we ...
🌐
Readthedocs
argparse.readthedocs.io › en › stable › defaults.html
Default values — argparse 0.7.1 tutorial
defmode property regulates how argparse should use the default value of an element. By default, or if defmode contains u (for unused), the default value will be automatically passed to the element if it was not invoked at all. It will be passed minimal required of times, so that if the element ...
🌐
Python
bugs.python.org › issue16399
Issue 16399: argparse: append action with default list adds to list instead of overriding - Python tracker
November 4, 2012 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/60603
🌐
GitHub
github.com › python › cpython › issues › 110131
Argparse: "Default" interacts incorrectly/non-intuitively with action='append' and action='extend' · Issue #110131 · python/cpython
September 30, 2023 - The fact that the values will be prepended to the end-user's input is not obvious, furthermore, the end-user is unable to specify a set of parameters that don't contain undesired default values. DEFAULT_SET=['a','b','c','d'] parser = argparse.ArgumentParser() parser.add_argument('--items',nargs='+',action='extend',dest='items',choices=DEFAULT_SET,default=DEFAULT_SET) args = parser.parse_args() print(args.items) $ python3 example.py --items a --items b c # expected: items will contain 'a', 'b', and 'c' ['a', 'b', 'c', 'd', 'a', 'b', 'c']
Author   rhetzler
🌐
Reddit
reddit.com › r/learnpython › argparse default values
r/learnpython on Reddit: argparse default values
March 21, 2017 -

I have a script that consists of several flags. Each flag, when stated following a filename, is set to true and runs a specific function.

prog.py myfile.txt -f

The above performs a specific function on myfile.txt that the -f flag is referring to. But I also want to be able to add arguments to the flag, so I set nargs=2.

prog.py myfile.txt -f 100 500

The above will run the program with myfile.txt and the arguments 100 and 500. No problems so far.

My issue is that I want to make it possible to run the same script even if no arguments are given. As in the first code, the script should run prog.py and perform the function that -f is referring to, but with default values, such as 10 and 50.

Now I know I could use Default when I add the argument to argparse, but then it will only use the default values if the -f flag is omitted. This is an issue because my script has many functions, and I want it to be capable of running a specific function depending on the flag that is used.

Basicallt I want the user to be able to perform function -f with or without any arguments, is there some way to achieve this?

I'm on Debian 8.7.1 using Python 2.7.13.

🌐
Janert
janert.me › blog › 2022 › command-line-arguments-with-pythons-argparse
Command Line Arguments with Python's Argparse Module - Philipp K. Janert, Ph.D.
November 11, 2022 - The default is "store", meaning that the value is stored in the object returned by parse_args(). Other possibilities include "count", which returns the number of times the option has been given on the command line, and a few others (see below). In addition to parsing the command-line arguments, ...
🌐
DataCamp
datacamp.com › tutorial › python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - By default, argparse does not display the parameters' default values in the help message.
🌐
Python
bugs.python.org › issue35495
Issue 35495: argparse does not honor default argument for nargs=argparse.REMAINDER argument - Python tracker
December 14, 2018 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/79676
🌐
DEV Community
dev.to › wincentbalin › print-default-values-of-cli-arguments-in-python-45ji
Print default values of CLI arguments in Python - DEV Community
July 2, 2019 - If you would like to print default values of command-line arguments and if you use the argparse.ArgumentParser class in your Python program, consider setting the formatter_class option to argparse.ArgumentDefaultsHelpFormatter.
🌐
Pydantic
docs.pydantic.dev › latest › concepts › pydantic_settings
Settings Management - Pydantic Validation
A CLI settings source can be integrated with existing parsers by overriding the default CLI settings source with a user defined one that specifies the root_parser object. import sys from argparse import ArgumentParser from pydantic_settings import BaseSettings, CliApp, CliSettingsSource parser = ArgumentParser() parser.add_argument('--food', choices=['pear', 'kiwi', 'lime']) class Settings(BaseSettings): name: str = 'Bob' # Set existing `parser` as the `root_parser` object for the user defined settings source cli_settings = CliSettingsSource(Settings, root_parser=parser) # Parse and load CLI settings from the command line into the settings source.
🌐
Flexiple
flexiple.com › python › python-argparse-list
Python argparse - Flexiple
March 27, 2024 - Argparse allows you to set default values for optional arguments. If users don't provide a value for an optional argument, argparse will use the default value you specified.
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print parser.parse_args(['-a', '-bval', '-c', '3']) There are a few ways to pass values to single character options. The example above uses two different forms, -bval and -c val. $ python argparse_short.py Namespace(a=True, b='val', c=3) The type of the value associated with 'c' in the output is an integer, since the ArgumentParser was told to convert the argument before storing it.
🌐
jdhao's digital space
jdhao.github.io › 2018 › 10 › 11 › python_argparse_set_boolean_params
Set up the Default Value for Boolean Option in Argparse · jdhao's digital space
November 3, 2019 - TL;DR If you want to set a parameter’s default value to True using argparse, use parser.add_argument('--param', action='store_false') Otherwise, use parser.add_argument('--param', action='store_true')