In add_argument()
, type
is just a callable object that receives string and returns option value.
import ast
def arg_as_list(s):
v = ast.literal_eval(s)
if type(v) is not list:
raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
return v
def foo():
parser.add_argument("--list", type=arg_as_list, default=[],
help="List of values")
This will allow to:
$ ./tool --list "[1,2,3,4]"