Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is argparse parents 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.

Multiple ArugumentParser objects often share the same arguments. It is redundant to specify the same arguments for every object. The argparse module provides the option to create a parent parser class that contains the shared arguments. The parent parser class can then be supplied to the parents argument of the ArgumentParser object.

Example

The following example demonstrates how to use shared arguments using a parent parser class.

The program creates a parent parser object parser with an argument x that is shared among parser2 and parser3.

parser is supplied to the parents argument of the parser2 and parser3 objects. The parents argument accepts a list of parent parser objects and adds the positional and optional arguments of the parent parser to the current object.

Notice that the add_help feature of the parent parser is turned off because otherwise, the two help options from the parent and child parsers will conflict and raise an error.

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(add_help = False)
# add arguments
parser.add_argument('-x', type = int, required = True, help='X')

args = parser.parse_args('-x 10'.split())
print(args)
# create an ArgumentParser object
parser2 = argparse.ArgumentParser(parents = [parser])
# add arguments
parser2.add_argument('-y', type = int, required = True, help='Y')

args2 = parser2.parse_args('-x 10 -y 30'.split())
print(args2)
# create an ArgumentParser object
parser3 = argparse.ArgumentParser(parents = [parser])
# add arguments
parser3.add_argument('-z', type = int, required = True, help='Z')

args3 = parser3.parse_args('-x 10 -z 30'.split())
print(args3)

RELATED TAGS

python

CONTRIBUTOR

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

View all Courses

Keep Exploring