Recommand · November 24, 2021 0

How to pass a list of tuples as an argument parameter?

I’m writing a python script where I want to pass in a list of tuples/list. I tried using the argparse module, but couldn’t find a way to pass in a list of tuples as an argument (i.e. [(1,2),(3,4),(5,6)]).

What I’ve tried so far:

  • I know I can use nargs='+' but that only enables me to pass in a list of values.
  • I tried parser.add_argument('--pairs', type=tuple, nargs='+'), but I get
 $ python --pairs (1,2) (2,4)
-bash: syntax error near unexpected token `('

Does anyone have any examples that uses the argparse module (or any other module for that matter)?

Here’s the script. Nothing special, just wanted to pass in the list of tuples and make sure I can print and access the elements properly:

import argparse

def test(args):

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--pairs', type=tuple, nargs='+')

    args = parser.parse_args()
    for arg in vars(args):
        print(arg, getattr(args, arg))


I figured a way, but please let me know if there’s a better one.

I used the ast module and passed the argument as a string and used the ast module (shoutout the answer I found here)

Here’s my updated code:

import argparse
import ast

def test(args):
    pairs = ast.literal_eval(args.pairs)
    print(args.pairs, type(args.pairs))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    args = parser.parse_args()


Testing this out yields:

$ python --pairs '[(1,2),(3,4)]'
[(1,2),(3,4)] <class 'str'>
<class 'list'>
(1, 2)