Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Argparse argument with default and optional value

  • nargs

  • const

  • Instead of default we use the const parameter here

  • We tell argparse that the value of the parameter is optional by nargs='?'

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--level',     help='Some level', type=int, const=10, nargs='?')
args = parser.parse_args()

print(args.level)
$ python argument_with_optional_value.py
None
$ python argument_with_optional_value.py --level
10
$ python argument_with_optional_value.py --level 20
20