As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

Answer from Jdog on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ argparse.html
argparse โ€” Parser for command-line options, arguments and subcommands
A subclass of Action for handling boolean flags with positive and negative options. Adding a single argument such as --foo automatically creates both --foo and --no-foo options, storing True and False respectively: >>> import argparse >>> parser ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ argparse.html
Argparse Tutorial โ€” Python 3.14.4 documentation
As should be expected, specifying the long form of the flag, we should get the same output. Sadly, our help output isnโ€™t very informative on the new ability our script has acquired, but that can always be fixed by improving the documentation for our script (e.g. via the help keyword argument). That last output exposes a bug in our program. ... import argparse parser = argparse.ArgumentParser() parser.add_argument("square", type=int, help="display a square of a given number") parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") args = parser.parse_args() answer = args.square**2 # bugfix: replace == with >= if args.verbosity >= 2: print(f"the square of {args.square} equals {answer}") elif args.verbosity >= 1: print(f"{args.square}^2 == {answer}") else: print(answer)
๐ŸŒ
Bite Code
bitecode.dev โ€บ p โ€บ parameters-options-and-flags-for
Parameters, options and flags for Python scripts
July 4, 2023 - In fact, a flag is just a special option. The Python command has the -c option, which let you execute code directly from the cmd. E.G: python -c "print('Wingarda Leviosum')" Wingarda Leviosum ยท The option print('Wingarda Leviosum') is the value ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ argparse: how do i add a flag that doesn't require an argument, but can take an argument optionally.
r/learnpython on Reddit: Argparse: How do I add a flag that doesn't require an argument, but can take an argument optionally.
July 1, 2021 -

Using argparse, how do you add a flag that doesn't require an argument, but can optionally take an argument.

Desired behaviour

$ keychart -c # outputs a csv to wherever PWD the script is runing from 
$ keychart -c /home/nick/csv # outputs a csv to specified directory

At present, my code that (almost) does what I want, but won't handle being given an argument:

# 'scratch.py' 
import argparse 
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--csv", help="write results to a csv to disk", action='store_true')
print(args.csv)

# works as desired
$ python3 scratch.py -c
True

# doesn't work as desired
$ python3 scratch.py -c testo
usage: scratch.py [-h] [-c]
scratch.py: error: unrecognized arguments: testo

๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-are-argparse-names-or-flags-in-python
What are argparse names or flags in Python?
The program adds another argument, radius, and leaves it as an optional argument. The add_argument() function knows that the argument radius is optional because the first argument for this function is a flag.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ argparse
argparse โ€“ Command line option and argument parsing. - Python Module of the Week
$ python argparse_subparsers.py delete -r foo Namespace(dirname='foo', recursive=True) The examples so far have shown simple boolean flags, options with string or numerical arguments, and positional arguments.
Find elsewhere
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ argparse โ€บ index.html
argparse โ€” Command-Line Option and Argument Parsing
December 30, 2016 - $ python3 argparse_subparsers.py delete -r foo Namespace(dirname='foo', recursive=True) The examples so far have shown simple Boolean flags, options with string or numerical arguments, and positional arguments.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-argparse
Master Python's argparse Module: Build Better CLIs | DataCamp
December 3, 2024 - If the user enters a value that is not in the list, argparse will return an error message. Boolean flags are choices that enable or disable specific functionalities in your application. They are typically defined without a value, merely by including the flag in the command.
๐ŸŒ
Real Python
realpython.com โ€บ command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse โ€“ Real Python
December 14, 2024 - As you already know, a great feature of argparse is that it generates automatic usage and help messages for your applications. You can access these messages using the -h or --help flag, which is included by default in any argparse CLI.
๐ŸŒ
DEV Community
dev.to โ€บ usooldatascience โ€บ mastering-pythons-argparse-a-comprehensive-guide-for-beginners-48fn
Mastering Pythonโ€™s argparse: A Comprehensive Guide for Beginners - DEV Community
September 15, 2024 - If you don't provide the flag, the default value of False is used: $ python script.py Alice ยท argparse allows you to define both short and long option names for the same argument.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ argparse
Python argparse: Syntax, Usage, and Examples
In Python argparse, positional arguments are required by default. Optional arguments are created by adding a -- prefix: ... The --verbose flag is optional and behaves like a boolean switch.
๐ŸŒ
mkaz.blog
mkaz.blog โ€บ working-with-python โ€บ argparse
Parse Command-Line Arguments with Argparse
September 19, 2025 - The examples so far have been about flags, parameters starting with --, argparse also handles the positional args which are just specified without the flag.
๐ŸŒ
GitHub
github.com โ€บ python โ€บ cpython โ€บ issues โ€บ 101599
``argparse`` Prints options per flag name when only once is necessary ยท Issue #101599 ยท python/cpython
February 6, 2023 - Notice that the flag choices are printed out twice, once for each flag name. This is redundant and negatively impacts readability. The program should output: usage: argparse_test.py [-h] [-m {accuracy,precision,recall}] options: -h, --help show this help message and exit -m, --metric {accuracy,precision,recall} ... stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancementA feature request or enhancement
Author ย  Harrison-O
๐ŸŒ
Read the Docs
stackless.readthedocs.io โ€บ en โ€บ 2.7-slp โ€บ library โ€บ argparse.html
15.4. argparse โ€” Parser for command-line options, arguments and sub-commands โ€” Stackless-Python 2.7.15 documentation
The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like: ... When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional: >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-f', '--foo') >>> parser.add_argument('bar') >>> parser.parse_args(['BAR']) Namespace(bar='BAR', foo=None) >>> parser.parse_args(['BAR', '--foo', 'FOO']) Namespace(bar='BAR', foo='FOO') >>> parser.parse_args(['--foo', 'FOO']) usage: PROG [-h] [-f FOO] bar PROG: error: too few arguments
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ argparse
Python argparse - parsing command line arguments in Python with argparse module
September 24, 2024 - #!/usr/bin/python import argparse # help flag provides flag help # store_true actions stores argument as True parser = argparse.ArgumentParser() parser.add_argument('-o', '--output', action='store_true', help="shows output") args = parser.parse_args() if args.output: print("This is some output") The example adds one argument having two options: a short -o and a long --ouput.
๐ŸŒ
Foggyprogrammer
foggyprogrammer.com โ€บ argparse-optional-argument-and-flag
`argparse`: Optional Argument and Flag? โ€“ Foggy Programmer
August 30, 2024 - import argparse parser = argparse.ArgumentParser() parser.add_argument('--testrun', nargs='?', const=20, type=int, help='Run a sample (default=20) records to test configuration') print(parser.parse_args([])) # no args #> testrun=None print(parser.parse_args(['--testrun'])) # flag, show default #> testrun=20 print(parser.parse_args(['--testrun=50'])) # flag with sample specified #> testrun=50 print(parser.parse_args(['--testrun', '5'])) # flag with sample specified #> testrun=5
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ a simple guide to command line arguments with argparse
A Simple Guide To Command Line Arguments With ArgParse | Towards Data Science
January 21, 2025 - You can use a positional argument to eliminate the need to specify the --name flag before inputting the actual value. Below are two versions โ€“ the first without positional arguments (multiply.py), and the second using positional arguments ...
๐ŸŒ
W3docs
w3docs.com โ€บ python
Parsing boolean values with argparse
import argparse parser = argparse.ArgumentParser() parser.add_argument('--flag', type=bool, default=True, help='A boolean flag') args = parser.parse_args() print(args.flag)