Last modified: Apr 10, 2026 By Alexander Williams
Python Argparse Default Value Guide
Command-line interfaces make scripts powerful. The argparse module is Python's tool for building them. A key feature is setting default values. This guide explains how to use them effectively.
What is a Default Value?
A default value is what an argument uses if the user does not provide one. It makes your script more flexible and user-friendly. You do not force the user to type every single option.
Think of it like a preset. Your program has a sensible starting point. The user can change it if they need to. This is central to good CLI design.
Basic Syntax: The 'default' Parameter
You set a default value using the default parameter in add_argument(). The syntax is simple and clear.
import argparse
# Create the parser
parser = argparse.ArgumentParser(description="A simple file processor.")
# Add an argument with a default value
parser.add_argument('--input', default='data.txt',
help='Input file path (default: data.txt)')
# Parse the arguments
args = parser.parse_args()
# Use the argument
print(f"Processing file: {args.input}")
In this code, --input gets the value 'data.txt' by default. The user can override it by typing --input myfile.csv.
# Run without providing --input
$ python script.py
Processing file: data.txt
# Run with a custom value
$ python script.py --input report.pdf
Processing file: report.pdf
Types of Default Values
Defaults are not just strings. They can be integers, floats, lists, or even None. The type often matches the argument's type parameter.
Numeric Defaults
Use numbers for settings like verbosity levels or ports.
parser.add_argument('--port', type=int, default=8080,
help='Port to listen on (default: 8080)')
parser.add_argument('--threshold', type=float, default=0.5,
help='Score threshold (default: 0.5)')
Boolean and Flag Defaults
For boolean flags, the default is often False. Setting action='store_true' makes the flag True only when provided. Our Python Argparse Boolean Flags Guide covers this in detail.
# Flag is False by default, True if --verbose is used
parser.add_argument('--verbose', action='store_true', default=False,
help='Enable verbose output')
The Special 'None' Default
Using default=None is common. It shows the argument was not given. You can check for it later in your code to apply logic.
parser.add_argument('--config', default=None,
help='Custom config file (optional)')
args = parser.parse_args()
if args.config is None:
# Load the default configuration
config = load_default_config()
else:
# Load the user-specified file
config = load_config(args.config)
Advanced Default Behaviors
Using 'const' with 'default'
The const parameter stores a value when an argument is used without a value. It works with action='store_const'. The default is used when the argument is absent.
parser.add_argument('--mode', action='store_const', const='fast', default='safe',
help='Run in fast mode (default: safe)')
$ python script.py
# args.mode is 'safe'
$ python script.py --mode
# args.mode is 'fast'
Dynamic Defaults with Lambda or Functions
Sometimes the default needs to be calculated at runtime. You can use a function or a lambda. The function is called only if the argument is not provided by the user.
import datetime
def get_default_date():
"""Return tomorrow's date as a string."""
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
return tomorrow.isoformat()
parser.add_argument('--date', default=get_default_date,
help='Target date (default: tomorrow)')
Common Pitfalls and Best Practices
Mutable Defaults: A Classic Bug
Never use a mutable object like a list or dict as a direct default. It is shared across all parser instances, leading to unexpected behavior.
# WRONG: This is a bug!
parser.add_argument('--items', default=[], help='List of items')
# CORRECT: Use a function or None
parser.add_argument('--items', default=None, help='List of items')
# In your code later:
if args.items is None:
args.items = [] # Initialize a fresh, empty list
Clarity in Help Text
Always state the default value in the help text. It informs the user immediately. For more on building clear CLIs, see our Python Argparse Example: Command Line Arguments.
# Good help text
parser.add_argument('--output', default='./results',
help='Output directory path (default: ./results)')
Default vs. Required
An argument with a default is, by nature, not required. Setting required=True and a default is contradictory. Argparse will raise an error.
Conclusion
Mastering default values in argparse is crucial. It makes your scripts intuitive and robust. Use simple strings, numbers, or dynamic functions. Always avoid mutable defaults. Remember to document the default in your help text.
Defaults provide a safety net. They guide users while giving experts control. Start using them to build better command-line tools today.