How do you provide a short and a long form for the same flag, like -v and --verbose?
Short answer
Pass both flag strings as positional arguments to add_argument() in the order you want them displayed; argparse treats them as aliases for the same destination attribute, and by default uses the first long-form name (stripped of leading dashes) as the attribute name unless you…
Advertisement
AModel answer
Pass both flag strings as positional arguments to add_argument() in the order you want them displayed; argparse treats them as aliases for the same destination attribute, and by default uses the first long-form name (stripped of leading dashes) as the attribute name unless you override it with 'dest'.
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
args = parser.parse_args(["-v"])
print(args.verbose) # True -- both -v and --verbose set the same 'verbose' attributeReal-world example
Supporting both a quick short flag (-v) for interactive use and a clearer long flag (--verbose) for scripts, referencing the same option.
Likely follow-ups
- Can a single argument have more than two aliases, like -v, --verbose, and --debug all pointing to the same flag?
Related topics