Python: Case In-sensitive argparse “choices”

There are cases that we need to limit the options that a user will provide as command line arguments, to do this the easy way in python we…

Python: Case In-sensitive argparse “choices”
Photo by David Clode on Unsplash

There are cases that we need to limit the options that a user will provide as command line arguments, to do this the easy way in python we can use the argparse module which provides a nice way to validate / handle options.

More often i needed to limit the choices of a command line option, to do this i used something like the following:parser = argparse.ArgumentParser()parser.add_argument('--ssh-gw',
   action   = 'store',
   type     = str,
   help     = "SSH Gateway.",
   required = False,
   choices  = ["grvgw1","grvgw2","grvgw3","grvgw4"],
   default  = False)

I created a command line option named ‘ — ssh-gw’ which can accept as valid options any value from grvgw1,grvgw2,grvgw3,grvgw4, is pretty handy but it has a problem, hosts are case in-sensitive, this means that its absolutely logical and valid for a user to enter GRVGW1 instead of grvgw1, which in this case our code will fail and will nag with an error.kpatronas@nostromo:~/scripts$ ./ssh_conn.py --ssh-gw GRVGW1
usage: store_explorer.py [-h] [--ssh-gw {grvgw1,grvgw2,grvgw3,grvgw4}]
ssh_conn.py: error: argument --ssh-gw: invalid choice: 'GRVGW1' (choose from 'grvgw1', 'grvgw2', 'grvgw3', 'grvgw4')

You have some options here, which are kind of ugly and / or inefficient

  • Add in choices the same hosts in capital letters, which is ugly and inefficient also because it will not work in case of GRVgw1 as input.
  • Force user to use only small / capital letters which is ugly

And here is the clever and efficient option

By changing this option:type = str

To:type = str.lower

This will force all user input for this option to be converted to lower case, which will cover any kind of input, small letters, capital or even mixed.

It’s a very simple solution, probably dead simple, but this is the spirit of Python “keep it simple and stupid”.