Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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') 
like image 733
Peter Avatar asked Dec 23 '14 08:12

Peter


People also ask

How do you make Argparse argument optional?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() .

What does DEST mean in Argparse?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object. dest identifies an argument.

What is action Store_true in Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .


2 Answers

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.

like image 77
5gon12eder Avatar answered Sep 23 '22 10:09

5gon12eder


Using lower in the type is nice way of doing this, if you don't mind loosing the case information.

If you want to retain the case, you could define a custom choices class. The choices needs two methods, __contains__ (for testing in), and iteration (to list the choices).

class mylist(list):     # list subclass that uses lower() when testing for 'in'     def __contains__(self, other):         return super(mylist,self).__contains__(other.lower()) choices=mylist(['win64','win32']) parser = argparse.ArgumentParser() parser.add_argument("-p", choices=choices) print(parser.parse_args(["-p", "Win32"])) # Namespace(p='Win32') 

The help is:

usage: ipython [-h] [-p {win64,win32}]  optional arguments:   -h, --help        show this help message and exit   -p {win64,win32} 
like image 40
hpaulj Avatar answered Sep 22 '22 10:09

hpaulj