What is argparse dest in Python?

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 adds value as an attribute dest of the object. dest identifies an argument.

Explanation

  • The dest attribute of a positional argument equals the first argument given to the add_argument() function.
  • An optional argument’s dest attribute equals the first long option string without --. Any subsequent - in the long option string is converted to _.
  • If the long option string is not provided, dest equals the first short option string without -.

For an argument foo, a short option can be of the type -f, and a long option is of the --foo type.

Example

The following example demonstrates how the dest keyword is attributed to arguments.

  • The first argument, foobar in the program below, is positional. dest is equal to the first argument supplied to the add_argument() function, as illustrated.
  • The second argument, radius_circle, is optional. A long option string --radius supplied to the add_argument() function is used as dest, as illustrated.
  • The third argument supplies two short option arguments, out of which the first one, -x, is used for its dest attribute.
  • Finally, the dest attribute can be set manually by specifying the value of dest in the arguments of add_argument().
import math
import argparse
#create an ArgumentParser object
parser = argparse.ArgumentParser()
#Add arguments
#positional argument
parser.add_argument('foobar')
#optional argument 1
parser.add_argument('-r', '--radius-circle')
# optional argument 2
parser.add_argument('-x', '-y')
parser.add_argument('-n','--newarg', dest = 'new' )
obj = parser.parse_args('9 -r 1 -x 2 -n 5'.split())
print(obj)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved