how to argparse a type that is diffrent

I am trying try to make it so the python main.py –point 0,0 be the argument and to throw an argument if it does not follow the format like int, ‘,’ , int

I really have tried searching online and found you could do

parser.add_argument('--point',  type=int, metavar='pointneeded',required=True)

but I could not find a way to make type a int then comma then int.

is there a way or should I just check manually?

Answer

Pass a callable to the type argument which will validate the string. Here, you can choose between the 2 validation options:

  • Using regex
  • Using map() to int. With this option, you can choose to return the list of numbers already instead of string.
import argparse
import re

def comma_separated_int(arg):
    # Validation Option 1: Using regex
    # if re.match(r"^(d+,)*d+$", arg) is None:
    #     raise ValueError()

    # Validation Option 2: Using mapping to int
    int_list = list(map(int, arg.split(",")))

    # Response Option 1: If you want to return the string value e.g. "1,2,3"
    # return arg
    # Response Option 2: If you want to return the list[int] value e.g. [1, 2, 3]
    return int_list

parser = argparse.ArgumentParser()
parser.add_argument('--point',  type=comma_separated_int, metavar='pointneeded', required=True)
args = parser.parse_args()

print(args.point)

Output

$ python3 main.py --point 1
[1]
$ python3 main.py --point 12
[12]
$ python3 main.py --point 123
[123]
$ python3 main.py --point 1,2,3
[1, 2, 3]
$ python3 main.py --point 11,22,333
[11, 22, 333]
$ python3 main.py --point 11,2a,333
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '11,2a,333'
$ python3 main.py --point a
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: 'a'
$ python3 main.py --point abc
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: 'abc'
$ python3 main.py --point 1,
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '1,'
$ python3 main.py --point ,1
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: ',1'
$ python3 main.py --point 1,,2
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '1,,2'