Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept `choices` in Python argparse irrespective of case? [duplicate]

I have a flag in a Python program which can only be certain strings, rock, paper, or scissors. Python argparse has a great way to implement this, using choices, container of the allowable values for the argument.

Here's an example from the documentation:

import argparse
...
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
parser.parse_args(['rock'])
### Namespace(move='rock')
parser.parse_args(['fire'])
### usage: game.py [-h] {rock,paper,scissors}
### game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors')

I would like to implement choices such that the choices are not case-sensitive, i.e. users could input RoCK and it would still be valid.

What is the standard way to do this?

like image 414
ShanZhengYang Avatar asked Dec 20 '17 09:12

ShanZhengYang


People also ask

How do you make Argparse argument optional?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

What is Metavar in Argparse Python?

Metavar: It provides a different name for optional argument in help messages.


1 Answers

You can set type=str.lower.

See Case insensitive argparse choices

import argparse

parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'], type=str.lower)
parser.parse_args(['rOCk'])
# Namespace(move='rock')
like image 166
KPLauritzen Avatar answered Sep 30 '22 19:09

KPLauritzen