Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is allow_abbrev 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.

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

The parse_args() method allows abbreviations of long arguments to be written. It infers which argument is being indicated through the abbreviation. For instance, if a user wants to supply a value for an argument radius with a long option string as --radius, they will write --radius 20. Using abbreviations, they can write --rad 20.

However, an abbreviation can match more than one argument. In that case, the program throws an error. The allow_abbrev parameter supplied to the add_argument() function can turn this option off, and any attempt at using abbreviations will throw an error.

Examples

The following examples demonstrate how to use abbreviated supply values for arguments and turn this feature off.

Example 1

The following program uses the abbreviations --f and --rd for the arguments --foo and --radius, respectively. The program infers what arguments the values belong to, as illustrated:


import argparse

#create an ArgumentParser object
parser = argparse.ArgumentParser(description = 'Calculate radius of the circle')
#declare arguments
parser.add_argument('--foo')
parser.add_argument('--radius', type = int, help='radius of the circle')
args = parser.parse_args('--f bar --rd 30'.split())


print(args)
                       

Example 2

The following program uses the abbreviations --f and --rd for the arguments --foo and --radius, respectively. However, the abbreviations are disabled, so the program throws an error, as seen here:


import argparse

#create an ArgumentParser object
parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
#declare arguments
parser.add_argument('--foo')
parser.add_argument('--radius', type = int, help='radius of the circle')
args = parser.parse_args('--f bar --rd 30'.split())


print(args)
                       

RELATED TAGS

python

CONTRIBUTOR

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

View all Courses

Keep Exploring