pythonargparsecase-insensitive

Case insensitive argparse choices


Is it possible to check argparse choices in case-insensitive manner?

import argparse
choices = ["win64", "win32"]
parser = argparse.ArgumentParser()
parser.add_argument("-p", choices=choices)
print(parser.parse_args(["-p", "Win32"]))

results in:

usage: choices.py [-h] [-p {win64,win32}]
choices.py: error: argument -p: invalid choice: 'Win32' (choose from 'win64','win32')

Solution

  • Transform the argument into lowercase by using

    type=str.lower
    

    for the -p switch, i.e.

    parser.add_argument("-p", choices=choices, type=str.lower)
    

    This solution was pointed out by chepner in a comment. The solution I proposed earlier was

    type=lambda s: s.lower()
    

    which is also valid, but it's simpler to just use str.lower.