argparse
python
command-line
help-menu
default-values

Argparse Way to include default values in '--help'?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

By default, argparse does not show default values in the --help output. To include them, set formatter_class=argparse.ArgumentDefaultsHelpFormatter when creating the parser. This automatically appends (default: value) to every argument's help text. Alternatively, manually include %(default)s in individual help strings for selective display.

python
1import argparse
2
3parser = argparse.ArgumentParser(
4    description="Process some data",
5    formatter_class=argparse.ArgumentDefaultsHelpFormatter
6)
7
8parser.add_argument('--output', default='result.csv', help='Output file path')
9parser.add_argument('--verbose', action='store_true', help='Enable verbose logging')
10parser.add_argument('--workers', type=int, default=4, help='Number of worker threads')
11parser.add_argument('--rate', type=float, default=0.01, help='Learning rate')
12
13args = parser.parse_args()
bash
1$ python script.py --help
2usage: script.py [-h] [--output OUTPUT] [--verbose] [--workers WORKERS] [--rate RATE]
3
4Process some data
5
6options:
7  -h, --help         show this help message and exit
8  --output OUTPUT    Output file path (default: result.csv)
9  --verbose          Enable verbose logging (default: False)
10  --workers WORKERS  Number of worker threads (default: 4)
11  --rate RATE        Learning rate (default: 0.01)

Every argument automatically gets (default: ...) appended.

Method 2: %(default)s in Help String

For selective default display without changing the formatter:

python
1import argparse
2
3parser = argparse.ArgumentParser(description="Process data")
4
5# Only these show defaults
6parser.add_argument('--output', default='result.csv',
7                    help='Output file path (default: %(default)s)')
8parser.add_argument('--workers', type=int, default=4,
9                    help='Worker threads (default: %(default)s)')
10
11# This one does not show the default
12parser.add_argument('--debug', action='store_true',
13                    help='Enable debug mode')
14
15args = parser.parse_args()
bash
1$ python script.py --help
2options:
3  --output OUTPUT    Output file path (default: result.csv)
4  --workers WORKERS  Worker threads (default: 4)
5  --debug            Enable debug mode

Available Format Specifiers

python
1parser.add_argument('--count', type=int, default=10,
2                    help='Number of items (default: %(default)s, type: %(type)s)')
3# Output: Number of items (default: 10, type: int)
4
5# Available specifiers:
6# %(default)s  — the default value
7# %(type)s     — the type (int, float, str, etc.)
8# %(dest)s     — the destination variable name
9# %(prog)s     — the program name
10# %(choices)s  — the allowed choices (if set)

Combining with RawDescriptionHelpFormatter

If you need both raw description formatting and defaults, create a combined class:

python
1import argparse
2
3class CustomFormatter(argparse.RawDescriptionHelpFormatter,
4                      argparse.ArgumentDefaultsHelpFormatter):
5    pass
6
7parser = argparse.ArgumentParser(
8    description="""\
9My Tool
10-------
11A tool for processing data.
12Supports multiple formats.""",
13    formatter_class=CustomFormatter
14)
15
16parser.add_argument('--format', default='csv', choices=['csv', 'json', 'xml'],
17                    help='Output format')
18
19args = parser.parse_args()
bash
1$ python script.py --help
2My Tool
3-------
4A tool for processing data.
5Supports multiple formats.
6
7options:
8  --format {csv,json,xml}  Output format (default: csv)

Hiding Defaults for Specific Arguments

With ArgumentDefaultsHelpFormatter, suppress defaults selectively using argparse.SUPPRESS:

python
1parser = argparse.ArgumentParser(
2    formatter_class=argparse.ArgumentDefaultsHelpFormatter
3)
4
5parser.add_argument('--output', default='result.csv', help='Output file')
6# Shows: Output file (default: result.csv)
7
8parser.add_argument('--secret', default=argparse.SUPPRESS,
9                    help='Hidden option')
10# Shows: Hidden option
11
12parser.add_argument('--internal', help=argparse.SUPPRESS)
13# Completely hidden from --help

Subparsers with Defaults

python
1parser = argparse.ArgumentParser(
2    formatter_class=argparse.ArgumentDefaultsHelpFormatter
3)
4subparsers = parser.add_subparsers(dest='command')
5
6# Each subparser can have its own formatter
7train_parser = subparsers.add_parser(
8    'train',
9    formatter_class=argparse.ArgumentDefaultsHelpFormatter
10)
11train_parser.add_argument('--epochs', type=int, default=10, help='Training epochs')
12train_parser.add_argument('--lr', type=float, default=0.001, help='Learning rate')
13
14eval_parser = subparsers.add_parser(
15    'eval',
16    formatter_class=argparse.ArgumentDefaultsHelpFormatter
17)
18eval_parser.add_argument('--batch-size', type=int, default=32, help='Batch size')
bash
1$ python script.py train --help
2options:
3  --epochs EPOCHS  Training epochs (default: 10)
4  --lr LR          Learning rate (default: 0.001)

Environment Variable Defaults

python
1import argparse
2import os
3
4parser = argparse.ArgumentParser(
5    formatter_class=argparse.ArgumentDefaultsHelpFormatter
6)
7
8parser.add_argument(
9    '--host',
10    default=os.environ.get('APP_HOST', 'localhost'),
11    help='Server host (env: APP_HOST)'
12)
13parser.add_argument(
14    '--port',
15    type=int,
16    default=int(os.environ.get('APP_PORT', '8080')),
17    help='Server port (env: APP_PORT)'
18)
bash
1$ APP_HOST=0.0.0.0 python script.py --help
2options:
3  --host HOST  Server host (env: APP_HOST) (default: 0.0.0.0)
4  --port PORT  Server port (env: APP_PORT) (default: 8080)

Custom Default Display

python
1import argparse
2
3class SmartDefaultsFormatter(argparse.HelpFormatter):
4    """Show defaults only when they are not None."""
5    def _get_help_string(self, action):
6        help_text = action.help
7        if action.default is not None and action.default != argparse.SUPPRESS:
8            help_text += f' (default: {action.default})'
9        return help_text
10
11parser = argparse.ArgumentParser(formatter_class=SmartDefaultsFormatter)
12parser.add_argument('--output', default='result.csv', help='Output file')
13# Shows: Output file (default: result.csv)
14
15parser.add_argument('--config', help='Config file path')
16# Shows: Config file path (no default shown — it's None)

Common Pitfalls

  • Defaults not shown without formatter_class: The default HelpFormatter does not show defaults. You must explicitly set formatter_class=ArgumentDefaultsHelpFormatter or use %(default)s in help strings.
  • store_true showing (default: False): With ArgumentDefaultsHelpFormatter, boolean flags show (default: False), which can be confusing. Use a custom formatter to suppress None/False defaults.
  • %(default)s with None: If no default is set, %(default)s displays None. Set sensible defaults or use conditional formatting.
  • Formatter class not inherited by subparsers: Each subparser needs its own formatter_class. The parent parser's formatter does not propagate automatically.
  • Conflicting formatter classes: RawDescriptionHelpFormatter and ArgumentDefaultsHelpFormatter cannot both be passed to formatter_class. Create a combined class via multiple inheritance instead.

Summary

  • Set formatter_class=argparse.ArgumentDefaultsHelpFormatter for automatic default display on all arguments
  • Use %(default)s in individual help strings for selective default display
  • Combine formatter classes via multiple inheritance for both raw formatting and defaults
  • Use argparse.SUPPRESS to hide specific defaults or entire arguments from help
  • Create custom HelpFormatter subclasses for specialized default display logic

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.