Search code examples
pythonpython-2.7python-2.xoptional-arguments

Error because of variable length optionals arguments (*args) in Python 2


I am trying to run below code in python 2 but getting Invalid syntax error.

    columns = ["col1"]
    funcs = val_to_list(funcs)
    exprs = []

    for col_name in columns:
        for func in funcs:
            exprs.append((func, (col_name, *args)))

I took this code from Python 3 project but i want to make it work in Python 2. I tried few combinations but not working. Please help!


Solution

  • (col_name, *args) creates a new tuple with col_name as the first element, followed by all the elements from args. This syntax is called iterable unpacking and was first added to Python 3.5.

    Just create the tuple by concatenating:

    t =  (col_name,) + args  # assuming args is a tuple too
    exprs.append((func, t))
    

    If args is itself not yet a tuple, convert it:

    t =  (col_name,) + tuple(args)  # works with any iterable.
    exprs.append((func, t))