Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is argparse argument_default in Python?

Ayesha Naeem

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.

Explanation

The parse_args() function of the ArgumentParser class parses arguments and the add_argument() function adds arguments to be accepted from the user.

The user often supplies a default value of an argument in case a value is not specified. To provide a global, parser-wide default value for arguments, the argument_default attribute is used.

Example

The following code demonstrates how to use the default_argument argument.

The program provides the parser with three arguments, r, x, and foo. It also sets the default_argument to argparse.SUPPRESS. This means that the program will halt attribute creation if no values are provided for the arguments.

The program’s output illustrates that an empty object is returned when arguments are provided to the parse_args() function.

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(argument_default = argparse.SUPPRESS)
# add arguments
parser.add_argument('-r', type = int)
parser.add_argument('x', nargs = '?', )
parser.add_argument('--foo', type = int)
args = parser.parse_args('-r 2 5 --foo 5'.split())
print(args)
args = parser.parse_args(''.split())
print(args)

RELATED TAGS

python

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring