Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

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

By default, the ArgumentParser object does not allow an option string to be used by an argument if it’s already in use by another argument. If the user attempts to do so, an error is raised.

However, the conflict_hanfler = resolve attribute of the ArgumentParser object can enable the overriding of the older arguments with the same option string.

Example

The following program demonstrates how to override older arguments with the same option strings through the conflict_handler parameter.

  • The program creates two arguments, radius and L.
  • It then creates two new arguments using the same option strings as the first two arguments.
  • The third argument overrides the long option string of the first argument. The first argument retains because its short option string is not overridden.
  • The program removes the second argument because the last argument overrides all of its option strings.

If all the option strings of an argument are overridden, that argument is automatically removed.

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(conflict_handler = 'resolve')
# add arguments
parser.add_argument('-r', '--radius', help = 'old radius help')
parser.add_argument('-l', help = 'old length help', )
parser.add_argument('--radius', help = 'new radius help')
parser.add_argument('-l', help = 'new length help', )
parser.print_help()

RELATED TAGS

python

CONTRIBUTOR

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

View all Courses

Keep Exploring