Case insensitive argparse choices

Peter picture Peter · Dec 23, 2014 · Viewed 18.9k times · Source

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')

Answer

5gon12eder picture 5gon12eder · Dec 23, 2014

Transform the argument into lowercase by using

type = str.lower

for the -p switch.

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.