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
destattribute of a positional argument equals the first argument given to theadd_argument()function. - An optional argument’s
destattribute 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,
destequals 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--footype.
Example
The following example demonstrates how the dest keyword is attributed to arguments.
- The first argument,
foobarin the program below, is positional.destis equal to the first argument supplied to theadd_argument()function, as illustrated. - The second argument,
radius_circle, is optional. A long option string--radiussupplied to theadd_argument()function is used asdest, as illustrated. - The third argument supplies two short option arguments, out of which the first one,
-x, is used for itsdestattribute. - Finally, the
destattribute can be set manually by specifying the value ofdestin the arguments ofadd_argument().
import mathimport argparse#create an ArgumentParser objectparser = argparse.ArgumentParser()#Add arguments#positional argumentparser.add_argument('foobar')#optional argument 1parser.add_argument('-r', '--radius-circle')# optional argument 2parser.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