Search code examples
pythonargparse

python argparse - How to prevent by using a combination of arguments


In argparse, I want to prevent a particular combination of arguments. Lets see the sample code.

Sample:

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--firstname', dest='fn', action='store')
parser.add_argument('--lastname', dest='ln', action='store')
parser.add_argument('--fullname', dest='full', action='store')
args = parser.parse_args()

For eg: --firstname --lastname --fullname

The user can run the code in 2 days.

Way 1:

code.py --firstname myfirst --lastname mylast

Way 2:

code.py --fullname myfullname

Prevent

We should not use the combination fistname, fullname or lastname, fullname. If we use both, then it should not execute.

Can someone help me to fix this?


Solution

  • Like this answer proposes (on a similar question) you can do something like the following by using subparsers for both cases:

    # create the top-level parser
    parser = argparse.ArgumentParser(add_help=false)
    subparsers = parser.add_subparsers(help='help for subcommands')
    
    # create the parser for the "full_name" command
    full_name = subparsers.add_parser('full_name', help='full_name help')
    full_name.add_argument('--fullname', dest='full', action='store')
    
    # create the parser for the "separate_names" command
    separate_names = subparsers.add_parser('separate_names', help='separate_names help')
    separate_names.add_argument('--firstname', dest='fn', action='store')
    separate_names.add_argument('--lastname', dest='ln', action='store')
    
    args = parser.parse_args()
    

    You can improve it even further by requiring both the first and last name of the user as it generally makes sense.