How to create an argument of type "list of pairs" using argparse?

I need the end user of my python script to write something like:

script.py -sizes <2,2> <3,3> <6,6> 

where each element of the -sizes option is a pair of two positive integers. How can I achieve this with argparse ?

+6
source share
2 answers

Define a custom type:

 def pair(arg): # For simplity, assume arg is a pair of integers # separated by a comma. If you want to do more # validation, raise argparse.ArgumentError if you # encounter a problem. return [int(x) for x in arg.split(',')] 

then use this as a type for a regular argument:

 p.add_argument('--sizes', type=pair, nargs='+') 

Then

 >>> p.parse_args('--sizes 1,3 4,6'.split()) Namespace(sizes=[[1, 3], [4, 6]]) 
+7
source

Argparse does not attempt to cover all possible input formats. You can always get sizes as a string and parse them with a few lines of code:

 import argparse parser = argparse.ArgumentParser() parser.add_argument('--sizes', nargs='+') args = parser.parse_args() try: sizes = [tuple(map(int, s.split(',', maxsplit=1))) for s in args.sizes] except Exception: print('sizes cannot be parsed') print(sizes) 

"Special cases are not complex enough to break the rules."

+1
source

All Articles