Nono.MA

[Solved] AttributeError: module 'argparse' has no attribute 'BooleanOptionalAction'

JANUARY 31, 2022

The argparse.BooleanOptionalAction feature is only available in Python 3.9 and above.

If you try to run this code in Python 3.8 and below.

parser = argparse.ArgumentParser(
    description='Description of my argument parser.')
parser.add_argument(
    '-f',
    '--feature',
    action=argparse.BooleanOptionalAction,
    default=False,
    help='Description of your feature.',
)

You'll get this error.

python script.py              
Traceback (most recent call last):
  File "script.py", line 12, in <module>
    action=argparse.BooleanOptionalAction,
AttributeError: module 'argparse' has no attribute 'BooleanOptionalAction'

In Python 3.8, you can do the following.

parser = argparse.ArgumentParser(
    description='Description of my argument parser.')
parser.add_argument(
    '-f',
    '--feature',
    action='store_true',
    help='Description of your feature.',
)

Let's see a complete example of how you'd use the --feature flag or its -f shorthand.

Example for Python 3.9.

# Python 3.9
# script.py
#!/usr/bin/env python
# coding: utf-8
import argparse

parser = argparse.ArgumentParser(
    description='Description of my argument parser.')
parser.add_argument(
    '-f',
    '--feature',
    action=argparse.BooleanOptionalAction,
    default=False,
    help='Description of your feature.',
)
opt = parser.parse_args()
print(opt.feature)

Example for Python 3.8.

# Python 3.8
# script.py
#!/usr/bin/env python
# coding: utf-8
import argparse

parser = argparse.ArgumentParser(
    description='Description of my argument parser.')
parser.add_argument(
    '-f',
    '--feature',
    action='store_true',
    help='Description of your feature.',
)
opt = parser.parse_args()
print(opt.feature)

Running the program

Then, here's what's returned when the script is executed on the command line.

python script.py
# False

python script.py --feature
# True

python script.py -f
# True

I hope that helped!

Error